forked from rui-yan/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
super-palindromes.cpp
45 lines (40 loc) · 1.15 KB
/
super-palindromes.cpp
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
// Time: O(n^0.25 * logn)
// Space: O(logn)
class Solution {
public:
int superpalindromesInRange(string L, string R) {
const auto K = static_cast<int>(pow(10, (R.length() + 1) * 0.25));
const int64_t l = stol(L), r = stol(R);
int result = 0;
// count odd length
for (int k = 0; k < K; ++k) {
const string s = to_string(k), rev_s(s.rbegin(), s.rend());
int64_t v = stol(s + rev_s.substr(1));
v *= v;
if (v > r) {
break;
}
if (v >= l && is_palindrome(v)) {
++result;
}
}
// count even length
for (int k = 0; k < K; ++k) {
const string s = to_string(k), rev_s(s.rbegin(), s.rend());
int64_t v = stol(s + rev_s);
v *= v;
if (v > r) {
break;
}
if (v >= l && is_palindrome(v)) {
++result;
}
}
return result;
}
private:
bool is_palindrome(int64_t k) {
const string s = to_string(k), rev_s(s.rbegin(), s.rend());
return s == rev_s;
}
};