Armstrong Number
Problem
Given an integer n, return true if and only if it is an Armstrong number. The k-digit number n is an Armstrong number if and only if the sum of each of its digits raised to the power k equals n.
n = 153truedef is_armstrong(n):
k = len(str(n))
total = 0
x = n
while x > 0:
d = x % 10
total += d ** k
x //= 10
return total == n
function isArmstrong(n) {
const k = String(n).length;
let total = 0;
let x = n;
while (x > 0) {
const d = x % 10;
total += Math.pow(d, k);
x = Math.floor(x / 10);
}
return total === n;
}
class Solution {
public boolean isArmstrong(int n) {
int k = String.valueOf(n).length();
int total = 0;
int x = n;
while (x > 0) {
int d = x % 10;
total += (int) Math.pow(d, k);
x /= 10;
}
return total == n;
}
}
bool isArmstrong(int n) {
int k = to_string(n).size();
int total = 0;
int x = n;
while (x > 0) {
int d = x % 10;
total += (int) pow(d, k);
x /= 10;
}
return total == n;
}
Explanation
An Armstrong number is one that equals the sum of each of its digits raised to the power of how many digits it has. So we just need to compute that sum and compare it to the original number.
First we count the digits: k = len(str(n)). Then we peel digits off the number one at a time using modulo and division: d = x % 10 grabs the last digit, and x //= 10 chops it off. For each digit we add d ** k to a running total.
When x reaches 0 we've processed every digit. The number is an Armstrong number exactly when total == n, so we return that comparison.
The order we visit digits (right to left) doesn't matter, since we're just summing independent terms.
Example: n = 153 has k = 3 digits. We compute 3^3 + 5^3 + 1^3 = 27 + 125 + 1 = 153, which equals n, so the answer is true.