Practice › Basics
Armstrong Number
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
A number with k digits is an Armstrong number if the sum of each digit raised to the power k equals the number (e.g. 153 = 1³ + 5³ + 3³). Print YES or NO.
Input
One integer n.
Output
YES or NO.
Constraints
- 1 ≤ n ≤ 10^9
Example 1
Input
153
Output
YES
Example 2
Input
123
Output
NO
Hints
- First count the digits k, then add up digit^k for every digit.
- Compute the power with integer multiplication — pow() on doubles can be off by one.
Approach
Two passes over the digits: the first counts them (k), the second adds digit^k. Compare the sum with n. Use an integer power loop and a 64-bit sum: for a 10-digit number the sum can reach 10 × 9^10 ≈ 3.5 × 10^10.
Complexity: O(k²) time for k digits · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
int k = to_string(n).size();
long long sum = 0;
for (long long x = n; x > 0; x /= 10) {
long long d = x % 10, p = 1;
for (int i = 0; i < k; i++) p *= d;
sum += p;
}
cout << (sum == n ? "YES" : "NO") << "\n";
return 0;
}Python solution
s = input().strip()
k = len(s)
total = sum(int(ch) ** k for ch in s)
print("YES" if total == int(s) else "NO")Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
int k = Long.toString(n).length();
long sum = 0;
for (long x = n; x > 0; x /= 10) {
long d = x % 10, p = 1;
for (int i = 0; i < k; i++) p *= d;
sum += p;
}
System.out.println(sum == n ? "YES" : "NO");
}
}