armstrong numbers problem java
import java.util.Scanner;
/*
*@author: Mayank Manoj Raicha
* Armstrong Number in Java: A positive number is called armstrong number if it is equal to the sum of cubes of its digits
* for example 0, 1, 153, 370, 371, 407 etc.
* 153 = (1*1*1)+(5*5*5)+(3*3*3) = 1+125+27 = 153
*/
public class ArmstrongNumberExample {
public static void main(String[] args) {
int sum = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number: ");
int input = in.nextInt(); //1634
String val = String.valueOf(input);
char[] charArray = val.toCharArray(); //charArray[0] = "1" , charArray[1] = "6", charArray[2] = "3", charArray[3] = "4"
int[] numArray = new int[charArray.length]; //Declaring this array to store the result of getPowerOfNumber() method for each digit.
//for each char element calculate the power of number and store it in the "cubedNumArray" array.
for(int i=0; i<charArray.length; i++) {
numArray[i] = getPowerOfNumber(Integer.parseInt(String.valueOf(charArray[i])), charArray.length);
sum = sum + numArray[i];
}
//Compare if the resulting sum is equal to the original input.
if(sum == input) {
System.out.println("Entered number is an Armstrong number.");
}else {
System.out.println("Entered number is NOT an Armstrong number.");
}
in.close();
}
//Calculate & Return the value of the first argument raised to the power of the second argument
public static int getPowerOfNumber(int num, int count) {
return (int) Math.pow(num, count);
}
}