An Armstrong (narcissistic) number equals the sum of its own digits each raised to the power of the digit count (e.g. 153 = 1^3 + 5^3 + 3^3).
Count the digits d, then sum each digit raised to the power d and compare to the original number. Extract digits with %10 and /10. O(number of digits) plus the power computations.
public static boolean isArmstrong(int n) {
int digits = String.valueOf(n).length();
int sum = 0, temp = n;
while (temp != 0) {
int d = temp % 10;
sum += (int) Math.pow(d, digits);
temp /= 10;
}
return sum == n;
}function isArmstrong(n) {
const digits = String(n).length;
const sum = String(n).split('')
.reduce((acc, d) => acc + Math.pow(Number(d), digits), 0);
return sum === n;
}def is_armstrong(n):
digits = len(str(n))
return n == sum(int(d) ** digits for d in str(n))A number-theory exercise that checks digit extraction and careful reading of the definition (power = digit count, not a fixed 3).
A candidate hardcodes the exponent to 3 and it fails for 9474 (a 4-digit Armstrong number). Fix?