File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n^0.25 * logn)
2
+ // Space: O(logn)
3
+
4
+ class Solution {
5
+ public:
6
+ int superpalindromesInRange (string L, string R) {
7
+ const auto K = static_cast <int >(pow (10 , (R.length () + 1 ) * 0.25 ));
8
+ const int64_t l = stol (L), r = stol (R);
9
+ int result = 0 ;
10
+
11
+ // count odd length
12
+ for (int k = 0 ; k < K; ++k) {
13
+ const string s = to_string (k), rev_s (s.rbegin (), s.rend ());
14
+ int64_t v = stol (s + rev_s.substr (1 ));
15
+ v *= v;
16
+ if (v > r) {
17
+ break ;
18
+ }
19
+ if (v >= l && is_palindrome (v)) {
20
+ ++result;
21
+ }
22
+ }
23
+
24
+ // count even length
25
+ for (int k = 0 ; k < K; ++k) {
26
+ const string s = to_string (k), rev_s (s.rbegin (), s.rend ());
27
+ int64_t v = stol (s + rev_s);
28
+ v *= v;
29
+ if (v > r) {
30
+ break ;
31
+ }
32
+ if (v >= l && is_palindrome (v)) {
33
+ ++result;
34
+ }
35
+ }
36
+
37
+ return result;
38
+ }
39
+
40
+ private:
41
+ bool is_palindrome (int64_t k) {
42
+ const string s = to_string (k), rev_s (s.rbegin (), s.rend ());
43
+ return s == rev_s;
44
+ }
45
+ };
You can’t perform that action at this time.
0 commit comments