Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits. Example: 13+53+33=153 which is same as given number 153., and 3 is the number of digits. 14+64+34+44=1634 which is same as given number 1634., and 4 is the number of digits.
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 |
package my.test; public class ArmstrongNumber { public static void main(String[] args) { System.out.println("Is 153 ArmsStrong Number: " + isArmstrongNumber(153)); System.out.println("Is 1634 ArmsStrong Number: " + isArmstrongNumber(1634)); System.out.println("Is 93084 ArmsStrong Number: " + isArmstrongNumber(93084)); System.out.println("Is 9800817 ArmsStrong Number: " + isArmstrongNumber(9800817)); System.out.println("Is 407 ArmsStrong Number: " + isArmstrongNumber(407)); System.out.println("Is 406 ArmsStrong Number: " + isArmstrongNumber(406)); } public static boolean isArmstrongNumber(int number) { if(number>0) { // Find number of digits in the given number.. int temp = number; int numberOfDigits = 0; while(temp>0) { temp =temp/10; numberOfDigits++; } //Power each digits with the number of digits.. int temp2 = number; int calcNumber = 0; while(temp2>0) { calcNumber = (int) (calcNumber + Math.pow((temp2%10), numberOfDigits)); temp2 = temp2/10; } if(calcNumber == number) { return true; } } return false; } } |