Strong Number
Problem
A strong number is equal to the sum of the factorials of its digits. Example: 145 = 1! + 4! + 5! = 1 + 24 + 120. Read a positive integer and print true if it is a strong number, otherwise false. (This is also called a Krishnamurthy number.)
Constraints
- 1 <= n <= 10^9
Examples
Input
145
Output
true
Input
123
Output
false
Solutions
The factorial of a digit is always one of ten values, so we store them in an array and look them up. We add the factorial of each digit and compare the sum with the number.
/*
* Problem : Check if a number is a strong number.
* Input : One integer.
* Output : true or false.
* Approach: Add the factorial of every digit.
* 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 strong number.
static boolean isStrong(long number) {
// Step 1: Only positive numbers are checked.
if (number < 1) {
return false;
}
// Step 2: Store the factorials of the digits 0 to 9. Example: factorial[4] = 24 because 4! = 4 * 3 * 2 * 1.
long[] factorial = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
// Step 3: Start the sum with 0.
long sum = 0;
long remaining = number;
// Step 4: Repeat until no digits are left.
while (remaining > 0) {
// Step 4a: Take the last digit and add its factorial to the sum. Example: 145 -> digit 5 -> 120.
sum = sum + factorial[(int) (remaining % 10)];
// Step 4b: Remove the last digit. Example: 145 / 10 = 14.
remaining = remaining / 10;
}
// Step 5: The number is strong 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(isStrong(number));
}
}
Hints (2)
- Which operator gives the last digit?
- Which operation removes the last digit?