153
is an Armstrong number because 1^3 + 5^3 + 3^3 = 153
.import java.util.Scanner;
public class ArmstrongNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
sc.close();
int originalNumber = number;
int numberOfDigits = 0;
// Count the number of digits
while (originalNumber != 0) {
originalNumber /= 10;
numberOfDigits++;
}
int sum = 0;
originalNumber = number;
// Calculate the sum of digits raised to the power of number of digits
while (originalNumber != 0) {
int digit = originalNumber % 10;
sum += Math.pow(digit, numberOfDigits);
originalNumber /= 10;
}
if (number == sum) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
}
Enter a number: 371
371 is an Armstrong number.
Enter a number: 870
870 is not an Armstrong number.
Scanner
class. We store the original number in a variable called originalNumber
, and count the number of digits in the number using a while
loop.while
loop. In each iteration of the loop, we extract the last digit of the number using the modulo operator %
, and add it to the sum after raising it to the power of number of digits using the Math.pow()
method. We then remove the last digit from the number using integer division /
.if
statement to check if the original number is equal to the sum. If they are equal, we print a message indicating that the number is an Armstrong number. Otherwise, we print a message indicating that the number is not an Armstrong number.