Java How To Check Armstrong Number
Check Armstrong Number
An Armstrong number is equal to the sum of its digits raised to the power of the number of digits (e.g. 153).
Example
int num = 153;
int original = num;
int result = 0;
int digits = String.valueOf(num).length();
while (num != 0) {
int digit = num % 10;
result += Math.pow(digit, digits);
num /= 10;
}
System.out.println(original + (result == original ? " is Armstrong" : " is not Armstrong"));
Explanation:
An Armstrong number means: take each digit, raise it to the power of the number of digits, and add them together.
For 153
(3 digits):
- First digit: 1³ = 1
- Second digit: 5³ = 125
- Third digit: 3³ = 27
Now add them: 1 + 125 + 27 = 153
.
Since the sum is the same as the original number, 153
is an Armstrong number.