This is the first solution to check the number for Armstrong. This solution uses String class, and a couple of Character functions to evaluate the sum of the cubes of each digit in a given number. The Armstrong number is say for a given number 153, evaluate the powers of cubes from any side as power (1 * 3) + power (5 * 3) + power (3 *3) , the sum of all powers must be equal to the given number 153.
public class ArmstrongNumbers {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sumCheck=0;
System.out.println("The Armstrong numbers between 1 to 1000");
for (int numValue=1;numValue<=1000;numValue++) {
// Convert the number to String for easy processing and to avoid the second loop
String numToStr=String.valueOf(numValue);
int numLen=numToStr.length();
// Calculate the sum of each digit's cube power value from any side
for (;numLen>0;numLen--)
if(Character.isDigit(numToStr.charAt(numLen-1)))
sumCheck = (int) (sumCheck + Math.pow(Character.getNumericValue(numToStr.charAt(numLen-1)),3));
//Compare the sumCheck with actual number
if (sumCheck == numValue)
System.out.println(numValue+" is Armstrong number");
//Reset sumCheck to 0 for next iteration
sumCheck=0;
}
}
}
Output:
The Armstrong numbers between 1 to 1000
1 is Armstrong number
153 is Armstrong number
370 is Armstrong number
371 is Armstrong number
407 is Armstrong number

Leave a comment