[LeetCode] Sum of k-Mirror Numbers

2081. Sum of k-Mirror Numbers

A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k.

  • For example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and 1001 respectively, which read the same both forward and backward.
  • On the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100, which does not read the same both forward and backward.

Given the base k and the number n, return the sum of the n smallest k-mirror numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#define ll unsigned long long
#define vll vector<ll>
#define all(a) begin(a), end(a)

class Solution {
bool kRadix(ll n, ll radix) {
string k;
while(n) {
k.push_back((n % radix) | 0b110000);
n /= radix;
}
reverse(all(k));
return palindrome(k);
}
bool kRadix(string s, ll radix) {
return kRadix(stoll(s), radix);
}
bool palindrome(string s) {
ll i = 0, j = s.length() - 1;
while(i < j)
if(s[i++] != s[j--])
return false;
return true;
}
public:
long long kMirror(int k, int n) {
ll res = 0;
queue<string> q;
for(ll i = 1; i <= 9 and n; i++) {
q.push(to_string(i));
if(kRadix(i,k)) {
n--;
res += i;
}
}

while(n) {
ll sz = q.size();
while(n and sz--) {
auto s = q.front(); q.pop();
auto _s = s;
reverse(all(_s));
auto ss = _s + s;
if(kRadix(ss,k)) {
n--;
res += stoll(ss);
}
q.push(s);
}

sz = q.size();
while(n and sz--) {
auto s = q.front(); q.pop();
auto _s = s;
reverse(all(_s));
for(ll i = 0; i <= 9 and n; i++) {
auto ss = _s + string(1,i + '0') + s;
if(kRadix(ss,k)) {
n--;
res += stol(ss);
}
q.push(string(1,i+'0') + s);
}
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/25/PS/LeetCode/sum-of-k-mirror-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.