Check Armstrong Number in Java
Check whether a number is an Armstrong number (sum of digits^number-of-digits equals the number).
IntermediateModule 2: Conditional ProgramsExample 5 of 20
check-armstrong-number.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);67 System.out.print("Enter a number: ");8 int n = sc.nextInt();910 int temp = n;11 int digits = 0;12 while (temp != 0) {13 digits++;14 temp /= 10;15 }1617 temp = n;18 int sum = 0;19 while (temp != 0) {20 int d = temp % 10;21 int pow = 1;22 for (int i = 0; i < digits; i++) {23 pow *= d;24 }25 sum += pow;26 temp /= 10;27 }2829 if (sum == n) {30 System.out.println(n + " is an Armstrong Number");31 } else {32 System.out.println(n + " is not an Armstrong Number");33 }3435 sc.close();36 }37}
Output
Enter a number: 153 153 is an Armstrong Number
What's going on
We raise each digit to the power of the total digits and add them; if the sum equals the original number, it is Armstrong.