Java program to check if a given number is an Armstrong number or not can be termed as a fresher
level
__interview question__. An ** Armstrong number** is a *number that is equal to the sum of the digits in a
number raised to the power of number of digits in the number*.

As Example if we take 371, it is an Armstrong number as the number of digits here is 3, so

371 = 3^{3}+ 7

^{3}+ 1

^{3}= 27 + 343 + 1 = 371

Another Example is 9474, here the number of digits is 4, so

9474 = 9^{4}+ 4

^{4}+ 7

^{4}+ 4

^{4}= 6561 + 256 + 2401 + 256 = 9474

And obviously 0 and 1 are also Armstrong number.

So let's write a Java program to check whether a given number is an Armstrong number or not.

package org.netjs.prgrm; 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

**Explanation**

Here the input is taken from the user, that number is converted to String just to get the length of the number. Logic here is to get one digit of the number at a time, starting from the last digit, get the value of that number power raised to the number of the digits and then divide the number by 10 to reduce the number by one digit. You can also add some conditions like checking for negative number, integer range etc.

That's all for this topic **Armstrong number - Java Program**. If you have any doubt or any
suggestions to make please drop a comment. Thanks!

__Related Topics__

**You may also like - **

## No comments:

## Post a Comment