1
+ class Solution {
2
+ public:
3
+ long long countGoodIntegers (int n, int k) {
4
+ unordered_set<string> st;
5
+
6
+ int d = (n+1 )/2 ;
7
+ int start = pow (10 ,d-1 );
8
+ int end = pow (10 ,d)-1 ;
9
+
10
+ for (int num = start; num<=end; num++){
11
+ string leftHalf = to_string (num);
12
+ string full = " " ;
13
+
14
+ if (n%2 == 0 ){
15
+ // n=4 --> 12 21
16
+ string rightHalf = leftHalf; // 12
17
+ reverse (rightHalf.begin (), rightHalf.end ());// 21
18
+ full = leftHalf + rightHalf; // 12 21
19
+ }else {
20
+ // 123 21
21
+ string rightHalf = leftHalf.substr (0 ,d-1 );
22
+ reverse (rightHalf.begin (), rightHalf.end ());// 21
23
+ full = leftHalf + rightHalf; // 123 21
24
+ }
25
+
26
+ // check div by k then palindrome/good
27
+ long long number = stoll (full); // 123 21
28
+ if (number % k !=0 )
29
+ continue ;
30
+
31
+ sort (full.begin (), full.end ());
32
+ st.insert (full);
33
+ }
34
+
35
+ // factorial precompute
36
+ vector<long long > factorial (11 ,1 );
37
+ for (int i=1 ;i<11 ;i++){
38
+ factorial[i] = factorial[i-1 ] * i;
39
+ }
40
+
41
+ long long result = 0 ;
42
+ // set par jao and saare palindrome ko pakdo
43
+ for (auto &s: st){
44
+ // to store the frequency of all
45
+ vector<int > count (10 ,0 );
46
+ for (auto &ch: s){
47
+ count[ch - ' 0' ]++;
48
+ }
49
+
50
+ int totalDigits = s.length ();
51
+ int zeroDigits = count[0 ];
52
+ int nonZeroDigits = totalDigits- zeroDigits;
53
+
54
+ long long perm = (nonZeroDigits * factorial[totalDigits-1 ]);
55
+
56
+ for (int i=0 ;i<10 ;i++){
57
+ perm /= factorial[count[i]];
58
+ }
59
+ result += perm;
60
+ }
61
+ return result;
62
+
63
+ }
64
+ };
0 commit comments