Skip to content

Instantly share code, notes, and snippets.

@elvismetaphor
Created December 6, 2016 09:50
Show Gist options
  • Save elvismetaphor/446d7144b21d8242362538d7f071ad73 to your computer and use it in GitHub Desktop.
Save elvismetaphor/446d7144b21d8242362538d7f071ad73 to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.Map;
public class SimilarNumberCounter {
private static Map<Integer, Integer> digitCounts = new HashMap<>();
private static void initializeDigitCounts() {
for (int i = 0; i <= 9; i++) {
digitCounts.put(i, 0);
}
}
/**
* Because the input number range from 0 to 99,999, only need to return int
*
* @param number the input number
* @return the count of the similar numbers
*/
private static int countSimilarNumbers(int number) {
countApparenceForDigits(number);
int length = countNumberLength(number);
int result = 0;
result = calcFactorial(length);
for (int i = 0; i <= 9; i++) {
result /= calcFactorial(digitCounts.get(i));
}
return result;
}
private static void countApparenceForDigits(int number) {
int currentValue = number;
while (currentValue > 0) {
int digit = currentValue % 10;
int count = digitCounts.get(digit);
digitCounts.put(digit, count + 1);
currentValue /= 10;
}
}
private static int countNumberLength(int number) {
return String.valueOf(number).length();
}
private static int calcFactorial(int number) {
int result = 1;
for (int i = 1; i <=number; i++) {
result = result * i;
}
return result;
}
public static void main(String[] args) {
int number = Integer.parseInt(args[0]);
initializeDigitCounts();
System.out.println("The count of similar numbers of " + number + " : "
+ countSimilarNumbers(number));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment