Armstrong Number in Java
An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
Examples:
- 153 → 1³ + 5³ + 3³ = 153
- 9474 → 9⁴ + 4⁴ + 7⁴ + 4⁴ = 9474
Java Program to Check Armstrong Number
import java.util.Scanner;
public class ArmstrongCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int original = number;
int result = 0;
int digits = String.valueOf(number).length();
while (number != 0) {
int digit = number % 10;
result += Math.pow(digit, digits);
number /= 10;
}
if (result == original) {
System.out.println(original + " is an Armstrong number.");
} else {
System.out.println(original + " is not an Armstrong number.");
}
}
}
Output
Enter a number: 153 153 is an Armstrong number.
Explanation
- The number of digits is calculated using
String.valueOf(number).length(). - Each digit is raised to the power of the total digits and added.
- If the sum matches the original number, it’s an Armstrong number.
Conclusion
This is a commonly asked Java interview question to test your knowledge of loops, conditionals, and number operations.