Last Updated: 14 Apr, 2021

Armstrong Number

Easy
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.
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

Approaches

01 Approach

  • 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.