|
| 1 | +// Problem Number: 3272 |
| 2 | + |
| 3 | +// Find the Count of Good Integers. |
| 4 | + |
| 5 | +class Solution { |
| 6 | + public long countGoodIntegers(int n, int k) { |
| 7 | + final int halfLength = (n + 1) / 2; |
| 8 | + final int minHalf = (int) Math.pow(10, halfLength - 1); |
| 9 | + final int maxHalf = (int) Math.pow(10, halfLength); |
| 10 | + long ans = 0; |
| 11 | + Set<String> seen = new HashSet<>(); |
| 12 | + |
| 13 | + for (int num = minHalf; num < maxHalf; ++num) { |
| 14 | + final String firstHalf = String.valueOf(num); |
| 15 | + final String secondHalf = new StringBuilder(firstHalf).reverse().toString(); |
| 16 | + final String palindrome = firstHalf + secondHalf.substring(n % 2); |
| 17 | + if (Long.parseLong(palindrome) % k != 0) |
| 18 | + continue; |
| 19 | + char[] sortedDigits = palindrome.toCharArray(); |
| 20 | + Arrays.sort(sortedDigits); |
| 21 | + String sortedDigitsStr = new String(sortedDigits); |
| 22 | + if (seen.contains(sortedDigitsStr)) |
| 23 | + continue; |
| 24 | + seen.add(sortedDigitsStr); |
| 25 | + int[] digitCount = new int[10]; |
| 26 | + for (char c : palindrome.toCharArray()) |
| 27 | + ++digitCount[c - '0']; |
| 28 | + |
| 29 | + final int firstDigitChoices = n - digitCount[0]; |
| 30 | + long permutations = firstDigitChoices * factorial(n - 1); |
| 31 | + |
| 32 | + for (final int freq : digitCount) |
| 33 | + if (freq > 1) |
| 34 | + permutations /= factorial(freq); |
| 35 | + ans += permutations; |
| 36 | + } |
| 37 | + |
| 38 | + return ans; |
| 39 | + } |
| 40 | + |
| 41 | + private long factorial(int n) { |
| 42 | + long res = 1; |
| 43 | + for (int i = 2; i <= n; ++i) |
| 44 | + res *= i; |
| 45 | + return res; |
| 46 | + } |
| 47 | +} |
0 commit comments