Armstrong Number

Easy
0/40
Average time to solve is 15m
profile
Contributed by
66 upvotes
Asked in companies
OracleIBMOptum

Problem statement

You are given an integer ‘NUM’ . Your task is to find out whether this number is an Armstrong number or not.

A k-digit number ‘NUM’ is an Armstrong number if and only if the k-th power of each digit sums to ‘NUM’.

Example
153 = 1^3 + 5^3 + 3^3.

Therefore 153 is an Armstrong number.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the ‘T’ test cases follow.

The first line of each test case contains a single positive integer, ‘NUM’.
Output Format:
For each test case, print ‘YES’ if it is an Armstrong number otherwise print ‘NO’.

The output of each test case will be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= ‘T’ <= 100
1 <= ‘N’ <= 10^9

Time Limit: 1 sec
Sample Input 1:
1
13
Sample Output 1:
NO
Explanation For Sample Input 1:
As 1^2 + 3^2 = 10 which is not equal to 13.So we can say it is not an Armstrong number.
Sample Input 2:
1
371
Sample Output 2:
YES
Hint

Initially find the number of digits in the number. Then find the sum of each digit to the power k and check if it is equal to the original number.

Approaches (1)
Maths
  • The first step will be to find the length of the number.
  • Initialize an integer k = 0, it will be used to find the length of the number.
  • Initialise an integer sum = 0.
  • Run a while loop till num is not equal to 0 (to calculate the length of number):
    • Increment k by 1.
  • Run a while loop till num is not equal to 0:
    • The current digit will be num%10.
    • Add (current digit) ^ k into sum.
    • Make num = num/10.
  • Check if ‘sum’ is equal to the initial number.
Time Complexity

O(log10(N)), where N is the number given to you.

 

We just need to traverse the digits of the number.

Space Complexity

O(1)

 

As we are using constant extra space.

Code Solution
(100% EXP penalty)
Armstrong Number
Full screen
Console