Checking whether a number is an Armstrong number in Java program is a classic fresher‑level interview question that tests both logical thinking and coding skills. An Armstrong number is a number that is equal to the sum of its digits each raised to the power of the total number of digits.
For Example-
- 371 is an Armstrong number because it has 3 digits, and
371 = 33 + 73 + 13 = 27 + 343 + 1 = 371 - 9474 is also an Armstrong number since it has 4 digits, and
9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474 - By definition, 0 and 1 are considered Armstrong numbers too.
Check given number Armstrong number or not
So let's write a Java program to check whether a given number is an Armstrong number or not. We'll break down how the logic works step by step later.
import java.util.Scanner;
public class ArmstrongNumber {
public static void main(String[] args) {
System.out.println("Please enter a number : ");
Scanner scanIn = new Scanner(System.in);
int scanInput = scanIn.nextInt();
boolean isArmstrong = checkForArmstrongNo(scanInput);
if(isArmstrong){
System.out.println(scanInput + " is an Armstrong number");
}else{
System.out.println(scanInput + " is not an Armstrong number");
}
scanIn.close();
}
private static boolean checkForArmstrongNo(int number){
// convert number to String
String temp = number + "";
int numLength = temp.length();
int numCopy = number;
int sum = 0;
while(numCopy != 0 ){
int remainder = numCopy % 10;
// using Math.pow to get digit raised to the power
// total number of digits
sum = sum + (int)Math.pow(remainder, numLength);
numCopy = numCopy/10;
}
System.out.println("sum is " + sum );
return (sum == number) ? true : false;
}
}
Some outputs-
Please enter a number : 125 sum is 134 125 is not an Armstrong number Please enter a number : 371 sum is 371 371 is an Armstrong number Please enter a number : 54748 sum is 54748 54748 is an Armstrong number
Armstrong number Java program explanation
In an Armstrong number Java program, the input number is first taken from the user. To determine the number of digits, the simplest approach is to convert the number into a string and use its length. This gives us the power to which each digit must be raised.
The logic works as follows:
- Extract digits one by one
- Start from the last digit using the modulus operator (num % 10).
- Raise this digit to the power of the total number of digits.
- Accumulate the sum
- Add the powered value to a running total.
- Reduce the number by one digit using integer division (num / 10).
- Repeat until all digits are processed
- Continue the loop until the number becomes zero.
- Compare with the original number
- If the accumulated sum equals the original number, it is an Armstrong number.
- Otherwise, it is not.
That's all for this topic Armstrong Number or Not Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment