给定数字N ,任务是检查给定数字是否为阿姆斯特朗数字。如果给定的号码是阿姆斯壮号码,则打印“是”,否则打印“否” 。
A positive integer of D digits is called an armstrong-numbers of order D (order is the number of digits) if
Where D is number of digit in number N
and N(1), N(2), N(3)… are digit of number N.
例子:
Input: N = 153
Output: Yes
Explanation:
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153
Input: 120
Output: No
Explanation:
120 is not an Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9
方法:想法是计算给定数字N中的位数(例如d )。对于给定数字N中的每个数字(例如r ),找到r d的值,如果所有值的总和为N,则打印“是”,否则打印“否” 。
下面是上述方法的实现:
C
// C program to find Armstrong number
#include
// Function to calculate N raised
// to the power D
int power(int N, unsigned int D)
{
if (D == 0)
return 1;
if (D % 2 == 0)
return power(N, D / 2)
* power(N, D / 2);
return N * power(N, D / 2)
* power(N, D / 2);
}
// Function to calculate the order of
// the number
int order(int N)
{
int r = 0;
// For each digit
while (N) {
r++;
N = N / 10;
}
return r;
}
// Function to check whether the given
// number is Armstrong number or not
int isArmstrong(int N)
{
// Calling order function
int D = order(N);
int temp = N, sum = 0;
// For each digit
while (temp) {
int Ni = temp % 10;
sum += power(Ni, D);
temp = temp / 10;
}
// If satisfies Armstrong condition
if (sum == N)
return 1;
else
return 0;
}
// Driver Code
int main()
{
// Given Number N
int N = 153;
// Function Call
if (isArmstrong(N) == 1)
printf("True\n");
else
printf("False\n");
return 0;
}
C++
// C++ program to find Armstrong number
#include
using namespace std;
// Function to calculate N raised
// to the power D
int power(int N, unsigned int D)
{
if (D == 0)
return 1;
if (D % 2 == 0)
return power(N, D / 2)
* power(N, D / 2);
return N * power(N, D / 2)
* power(N, D / 2);
}
// Function to calculate the order of
// the number
int order(int N)
{
int r = 0;
// For each digit
while (N) {
r++;
N = N / 10;
}
return r;
}
// Function to check whether the given
// number is Armstrong number or not
int isArmstrong(int N)
{
// To find order of N
int D = order(N);
int temp = N, sum = 0;
// Traverse each digit
while (temp) {
int Ni = temp % 10;
sum += power(Ni, D);
temp = temp / 10;
}
// If satisfies Armstrong condition
if (sum == N)
return 1;
else
return 0;
}
// Driver Code
int main()
{
// Given Number N
int N = 153;
// Function Call
if (isArmstrong(N) == 1)
cout << "True";
else
cout << "False";
return 0;
}
输出:
True
时间复杂度: O(log 10 N)
辅助空间: O(1)
想要从精选的最佳视频中学习和练习问题,请查看《基础到高级C的C基础课程》。