In the previous post, How to check Armstrong number java program we learned what is Armstrong number and How to write a Java program to test whether the given input number is Arm Strong or not.
In this post, I will show you a different approach to write the java program for Arm Strong number.
Below is the complete source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package kk.com.ArmStrong; import java.util.Scanner; public class ArmStrongTest { public static void main(String[] args) { Scanner scanner = null; try { scanner = new Scanner(System.in); System.out.println("Enter Number:"); int number = scanner.nextInt(); if(isArmStrong(number)) { System.out.println(number +" is armStrong"); }else { System.out.println(number +" is not armStrong"); } } catch (Exception e) { e.printStackTrace(); } } private static boolean isArmStrong(int number) { int originalNumber = number; int remainder; int sum =0; String valueOf = String.valueOf(number); int numberOfDights = valueOf.length(); //int numberOfDights =(""+number).length(); while(number !=0) { remainder = number % 10; sum = (int) (sum + Math.pow(remainder, numberOfDights)); number = number/10; } if(sum == originalNumber) return true; return false; } } |
Some Input/Output of this Program :
Enter Number:
171
171 is not armStrong
Enter Number:
371
371 is armStrong
You May Also Like:
Java Program to Calculate the Power of a Number
Check whether a number is prime or not
Java Program to displaying prime numbers
Fibonacci series using iterative and recursive approach java program
Find largest and second largest number in the given Array
Java program to Remove Duplicate Elements From an Array
Find common elements between two Arrays
Find largest and smallest number in the given Array
Java Program to find duplicate elements in an Array
That’s all in this post of Java Program for Armstrong number
If you have any feedback or suggestion please feel free to drop in below comment box.