Skip to content
thesarfo

Reference

Armstrong Numbers

Checking whether a number equals the sum of the cubes of its individual digits.

views 0

An Armstrong number is a number where adding the cube of all its individual digits sums back up to the number itself. Take 371: 3³ + 7³ + 1³ = 371, so it’s an Armstrong number.

We reuse the digit-extraction logic, cubing each digit as we go, and compare the running sum against the original number:

static void armstrong(int n){
int duplicate = n; // store the input number in this duplicate variable since n will change on each iteration
int sum = 0;
while (n > 0){
int lastDigit = n % 10;
sum = sum + (lastDigit * lastDigit * lastDigit); // each digit cubed will be stored into sum
n = n / 10;
}
if ( sum == duplicate){
return "true";
} else{
return "false";
}
}