This is the second solution to check the number for Disarium. This solution contains the core logic to evaluate the sum of powers of all digits in descending order of the length of number. 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 DisariumNumbersCorelogic {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inpInt= new Scanner (System.in);
int sumCheck=0, remValue;
System.out.println("Enter an integer value");
int numValue=inpInt.nextInt();
// Convert the number to String to find number of digits in the given number
String numToStr=String.valueOf(numValue);
int numLen=numToStr.length();
int storeNum=numValue;
// Calculate the sum of each digit's power value from high(=length of number) to 1
while(storeNum != 0) {
remValue=storeNum %10;
sumCheck = (int) (sumCheck + Math.pow(remValue, numLen));
storeNum=storeNum/10;
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