-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0906.cpp
More file actions
executable file
·60 lines (53 loc) · 1.23 KB
/
LC0906.cpp
File metadata and controls
executable file
·60 lines (53 loc) · 1.23 KB
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
/*
Problem Statement: https://leetcode.com/problems/super-palindromes/
Time: O(limit • log limit) = O(50'000 • log 50'000)
Space: O(log limit) = O(log 50'000)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
private:
int64_t reverse(int64_t num) {
int64_t rev = 0;
while (num) {
rev = 10 * rev + num % 10;
num /= 10;
}
return rev;
}
int64_t generate_palindrome(int64_t prefix, int64_t suffix) {
while (suffix) {
prefix = 10 * prefix + suffix % 10;
suffix /= 10;
}
return prefix;
}
public:
int superpalindromesInRange(string left, string right) {
int64_t num, l, r;
int cnt = 0, limit = 50'000;
l = sqrt(stoll(left));
r = sqrt(stoll(right));
// helper functions
auto is_super_palindrome = [&](int64_t num) {
if (num < l || num > r)
return false;
num *= num;
return num == reverse(num);
};
// even length palindromes
for (int i = 1; i <= limit; i++) {
int64_t num = generate_palindrome(i, i);
if (num > r)
break;
cnt += is_super_palindrome(num);
}
// odd length palindromes
for (int i = 1; i <= limit; i++) {
num = generate_palindrome(i, i / 10);
if (num > r)
break;
cnt += is_super_palindrome(num);
}
return cnt;
}
};