This is the first solution to check the number for Disarium. This solution uses String class, and a couple of Character functions to evaluate the sum of powers. The Disarium number is say for a given number 351, evaluate the powers from the left side as power (3 * 1) + power (5 * 2) + power (1 *3) , the sum of all powers must be equal to the given number 351.
import java.util.Scanner;
public class Disarium {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inpInt= new Scanner (System.in);
int sumCheck=0;
System.out.println("Enter an integer value");
int numValue=inpInt.nextInt();
// 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 power value from high(=length of number) to 1
for (;numLen>0;numLen--)
if(Character.isDigit(numToStr.charAt(numLen-1)))
sumCheck = (int) (sumCheck + Math.pow(Character.getNumericValue(numToStr.charAt(numLen-1)),numLen));
//Compare the sumCheck with actual number
if (sumCheck == numValue)
System.out.println("The given number "+numValue+" is Disarium");
else
System.out.println("The given number "+numValue+" is not Disarium");
inpInt.close();
}
}
Output:
Enter an integer value
135
The given number 135 is Disarium

Leave a comment