This is the second solution to check the number for Disarium. This solution uses IntStream, reduce methods of Stream. 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;
import java.util.stream.IntStream;
public class DisariumNumberUsingStream {
public static void main(String args[]) {
try (Scanner inpInt = new Scanner(System.in)) {
System.out.print("Enter a number to check for Disarium or not=");
int inpNum = inpInt.nextInt();
System.out.println("The given number is=" + inpNum);
String strVal = String.valueOf(inpNum);
/*
* Applying map and reduce method to find out the sum of powers based on each
* digit position in the give number
*/
int sumOfPowerDigits = IntStream.range(0, String.valueOf(inpNum).length()).reduce(0,
(x, y) -> x + (int) Math.pow(Character.getNumericValue(strVal.charAt(y)), y + 1));
/* Check whether computed sum is equal to the actual number */
if (sumOfPowerDigits == inpNum)
System.out.println("The given number " + inpNum + " is an Disarium");
else
System.out.println("The given number " + inpNum + " is not an Disarium");
}
}
}
Output:
Enter a number to check for Disarium or not=518
The given number is=518
The given number 518 is an Disarium
Output:
Enter a number to check for Disarium or not=241
The given number is=241
The given number 241 is not an Disarium

Leave a comment