Check Armstrong Number in Java
Problem
An Armstrong number (also called a narcissistic number) is a number equal to the sum of its own digits, each raised to the power of the total digit count.
Given a number, determine whether it is an Armstrong number.
Java Program
public class ArmstrongCheck {
public static void main(String[] args) {
int num = 153;
int digitCount = String.valueOf(num).length();
int original = num;
int sum = 0;
while (num > 0) {
int digit = num % 10; // peel off the last digit
sum += (int) Math.pow(digit, digitCount);
num /= 10; // drop the digit just processed
}
System.out.println(original + " is an Armstrong number: " + (sum == original));
}
}Output
Core Logic
Extracting each digit with % and /, raising it to the power of the digit count, and summing the results checks the definition directly.
- 1
digitCountis found by converting the number to aStringand reading itslength(). - 2The loop peels off one digit at a time with
num % 10, then removes it fromnumwithnum /= 10. - 3Each digit is raised to the power of
digitCountwithMath.pow()and added intosum. - 4Once every digit has been processed,
sumis compared against the original number.
153 (3 digits), the digits 1, 5, 3 raised to the third power give 1, 125, and 27 — summing to 153, which matches the original number.Key Point: Math.pow() returns a double, so the result is cast back to int before adding it to the running sum — with small digit counts this never loses precision.
Why: The loop runs once per digit, so the work scales with the number of digits, not the number's magnitude, and only a few running variables are kept.
Key Concepts
Approach 2: Java 8
public class ArmstrongCheckStream {
public static void main(String[] args) {
int num = 153;
int digitCount = String.valueOf(num).length();
// Converts each digit character back to a number, raises it to the digit count, and sums
int sum = String.valueOf(num).chars()
.map(c -> (int) Math.pow(c - '0', digitCount))
.sum();
System.out.println(num + " is an Armstrong number: " + (sum == num));
}
}
Output
Core Logic
The same digit-by-digit power sum can be expressed as a stream over the number's character digits.
- 1
String.valueOf(num).chars()returns anIntStreamof the number's digit characters. - 2
.map(c -> (int) Math.pow(c - '0', digitCount))converts each character back to a digit withc - '0', then raises it to the digit count. - 3
.sum()reduces the stream of powered digits down to a single total.
153, the stream maps '1', '5', '3' to 1, 125, and 27, and .sum() adds them up to 153.Key Point: c - '0' is the standard trick for converting a digit character to its numeric value, relying on digit characters being contiguous in Unicode.
Why: The stream still visits each digit character once, and sum() reduces directly to a single int without collecting anything.