[LeetCode] Super Palindromes

906. Super Palindromes

Let’s say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.

Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].

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
class Solution {
bool isP(unsigned long long llp) {
string p = to_string(llp);
int l = 0, r = p.length() -1;
while(l <= r) {
if(p[l] != p[r]) return false;
l++; r--;
}
return true;
}
unordered_set<unsigned long long> makePalindromes() {
unordered_set<unsigned long long> prefix = {1,2}, temp = prefix, res = {1,2,3};
for(int i = 0; i < 4; i++) {
unordered_set<unsigned long long> nTemp;
for(auto& tmp : temp) {
nTemp.insert(tmp * 10);
prefix.insert(tmp * 10);
nTemp.insert(tmp * 10 + 1);
prefix.insert(tmp * 10 + 1);
nTemp.insert(tmp * 10 + 2);
prefix.insert(tmp * 10 + 2);
}
swap(temp, nTemp);
}

for(auto& p : prefix) {
string l = to_string(p);
string r = l; reverse(r.begin(), r.end());
res.insert(stoll(l + r));
res.insert(stoll(l + '0' + r));
res.insert(stoll(l + '1' + r));
res.insert(stoll(l + '2' + r));
}
return res;
}
public:
int superpalindromesInRange(string left, string right) {
unordered_set<unsigned long long> palindromes = makePalindromes();

unsigned long long L = stoll(left), R = stoll(right);
int res = 0;

for(auto& p : palindromes) {
unsigned long long superP = p * p;
if(L <= superP and superP <= R and isP(superP)) {
++res;
}

}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/02/PS/LeetCode/super-palindromes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.