Check if the given number is an Armstrong Number or not in Java.
package Interview;
import java.util.Arrays;
public class ArmstrongNumber {
public static void main(String[] args) {
//153 is an Armstrong Number as 153= 1+ 125+27 which comes from 1^3+5^3+3^3
int givenNum = 9474;
String givenNumStr = Integer.toString(givenNum);
int len = givenNumStr.length();
int[] numArr = new int[len];//To put each individual integer
int[] numArr1 = new int[len];//To put each individual calculated value
int calculatedNum =0;
for(int i=0;i<len;i++) {
numArr[i]=Integer.parseInt(Character.toString(givenNumStr.charAt(i)));
numArr1[i]= (int) Math.pow(numArr[i], len) ;
calculatedNum = numArr1[i]+calculatedNum;
}
System.out.println("Each individual digit: "+Arrays.toString(numArr));
System.out.println("Each individual calculated value: "+Arrays.toString(numArr1));
System.out.println("Sum of calculated values: "+calculatedNum);
if (calculatedNum==givenNum) {
System.out.println(givenNum+" is an Armstrong Number");
} else {
System.out.println(givenNum+" is NOT an Armstrong Number");
}
}
}
Output:
Each individual digit: [9, 4, 7, 4]
Each individual calculated value: [6561, 256, 2401, 256]
Sum of calculated values: 9474
9474 is an Armstrong Number
No comments:
Post a Comment