Armstrong Numbers in Range

Print all Armstrong numbers in a given range.

JavaIntermediate
Java
public class Main {
    private static boolean isArmstrong(int n) {
        int temp = n;
        int digits = 0;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        temp = n;
        int sum = 0;
        while (temp != 0) {
            int d = temp % 10;
            int pow = 1;
            for (int i = 0; i < digits; i++) {
                pow *= d;
            }
            sum += pow;
            temp /= 10;
        }
        return sum == n;
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 1000; i++) {
            if (isArmstrong(i)) {
                System.out.print(i + " ");
            }
        }
    }
}

Output

Armstrong numbers between 1 and 1000: 1 153 370 371 407

We define a helper to check Armstrong and loop over a range, printing numbers that satisfy the condition.