Armstrong Numbers
An Armstrong number equals the sum of each decimal digit raised to the number of digits. Determine whether n has this property.
Work through the cases
3 examplesInput notation
An integer n from 0 through 1000000000.Expected result
true or false.Case 1
Input
370
Expected output
true
Case 2
Input
123
Expected output
false
Case 3
Input
0
Expected output
true
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Count the digits and add each digit raised to that count. Compare the sum with the original value. Time: O(d²) using repeated multiplication; extra space: O(d) for digit text.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Long> values = new ArrayList<>();
while (in.hasNextLong()) values.add(in.nextLong());
long[] a = values.stream().mapToLong(Long::longValue).toArray();
long n = a[0];
String digits = Long.toString(n); long sum = 0; for (char c : digits.toCharArray()) { long p = 1; for (int i = 0; i < digits.length(); i++) p *= c - '0'; sum += p; } System.out.println(sum == n);
}
}
Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.