Disarium Number
Problem
A Disarium number is equal to the sum of its digits raised to the power of their position, counted from the left starting at 1. Example: 89 = 8^1 + 9^2 = 8 + 81. Read a positive integer and print true if it is a Disarium number, otherwise false.
Constraints
- 1 <= n <= 10^12
Examples
Input
89
Output
true
Input
90
Output
false
Solutions
Taking digits with % 10 gives them from right to left. The last digit has the position equal to the digit count, so we start with that position and count down.
/*
* Problem : Check if a number is a Disarium number.
* Input : One integer.
* Output : true or false.
* Approach: Raise each digit to the power of its position.
* Time : O(d)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method receives a number and returns true if the number is a Disarium number.
static boolean isDisarium(long number) {
// Step 1: Only positive numbers are checked.
if (number < 1) {
return false;
}
// Step 2: Count the digits. Example: 89 has 2 digits.
int digitCount = String.valueOf(number).length();
// Step 3: The last digit has the position equal to the digit count. Example: in 89, the digit 9 is at position 2.
int position = digitCount;
long sum = 0;
long remaining = number;
// Step 4: Take the digits from the right to the left and count the position down.
while (remaining > 0) {
// Step 4a: Take the last digit. Example: 89 % 10 = 9.
long digit = remaining % 10;
// Step 4b: Raise the digit to the power of its position and add it to the sum. Example: 9^2 = 81.
sum = sum + Math.round(Math.pow(digit, position));
// Step 4c: Move to the next digit on the left.
position--;
remaining = remaining / 10;
}
// Step 5: The number is a Disarium number if the sum equals the number.
return sum == number;
}
public static void main(String[] args) {
long number = new Scanner(System.in).nextLong();
System.out.println(isDisarium(number));
}
}
Hints (2)
- Count the digits first.
- The position of the last digit is the digit count.