Armstrong Number — Solution in Python, Java & C++
Armstrong Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on math.
Armstrong Number is an easy coding problem on math, asked in TCS, Infosys, Wipro and Accenture interviews.
- Difficulty: Easy
- Topics: Math
- Asked at: TCS, Infosys, Wipro, Accenture, Capgemini, Mindtree, Mphasis
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A number is an Armstrong number (also called a narcissistic number) when the sum of its own digits, each raised to the power of the number of digits, equals the number itself.
Given a positive integer n, return true if n is an Armstrong number.
Example 1
Input: n = 153
Output: true
Explanation: It has 3 digits and 1³ + 5³ + 3³ = 1 + 125 + 27 = 153.
Example 2
Input: n = 123
Output: false
Explanation: 1³ + 2³ + 3³ = 36, not 123.
Example 3
Input: n = 9474
Output: true
Explanation: 9⁴ + 4⁴ + 7⁴ + 4⁴ = 9474.
Constraints
1 <= n <= 1000000
Hints for Armstrong Number
Hint 1
Count the digits first — that count is the exponent every digit is raised to.
Hint 2
Then sum
digit ^ kover the digits and compare with the original number.Hint 3
Single-digit numbers are all Armstrong numbers, since d¹ = d.
How to solve Armstrong Number
Count the digits to fix the exponent, then compare the sum of each digit raised to that power with the number.
Approach
- Let
kbe the number of digits ofn. - Sum
d^kover every digitd. - Return whether the sum equals
n.
Why it works
That is the definition; the only subtlety is that the exponent is the total digit count and must be computed before the summation begins.
Complexity
- Time —
O(k) - Space —
O(1)
Pitfalls
- Using a fixed exponent of 3 only tests the three-digit case —
9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴is Armstrong too. - Every single-digit number qualifies, since
d¹ = d.
Reference solution
Python
def isArmstrong(n: int) -> bool:
s = str(n)
k = len(s)
return sum(int(ch) ** k for ch in s) == nJava
public static boolean isArmstrong(int n) {
String s = String.valueOf(n);
int k = s.length();
long total = 0;
for (int i = 0; i < k; i++) {
long d = s.charAt(i) - '0';
long p = 1;
for (int e = 0; e < k; e++) p *= d;
total += p;
}
return total == n;
}C++
bool isArmstrong(int n) {
string s = to_string(n);
int k = (int) s.size();
long long total = 0;
for (int i = 0; i < k; i++) {
long long d = s[i] - '0';
long long p = 1;
for (int e = 0; e < k; e++) p *= d;
total += p;
}
return total == (long long) n;
}JavaScript
var isArmstrong = function(n) {
const s = String(n);
const k = s.length;
let total = 0;
for (let i = 0; i < k; i++) {
total += Math.pow(s.charCodeAt(i) - 48, k);
}
return total === n;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.