-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem036.cpp
57 lines (54 loc) · 1.28 KB
/
problem036.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
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <vector>
bool isPalindrome(int n)
{
int reverse = 0;
int x = n;
while (x != 0) {
reverse = 10 * reverse + x % 10;
x /= 10;
}
return reverse == n;
}
std::vector<int> doubleBasePalindromes(int upper)
{
std::vector<int> results;
// Generates all binary palindromes up to the upper limit.
for (int i = 1;; ++i) {
int reverse = 0;
int len = 0;
int x = i;
do {
reverse = (reverse << 1) | (x & 1);
x >>= 1;
++len;
} while (x != 0);
int even = (i << len) | reverse;
int odd = (i << (len - 1)) | reverse;
if (even <= upper) {
if (isPalindrome(even)) {
results.push_back(even);
}
if (isPalindrome(odd)) {
results.push_back(odd);
}
} else if (odd <= upper) {
if (isPalindrome(odd)) {
results.push_back(odd);
}
} else {
break;
}
}
return results;
}
int main()
{
int ans = 0;
std::vector<int> results = doubleBasePalindromes(999999);
for (int i = 0; i < results.size(); ++i) {
ans += results[i];
}
std::cout << "Answer: " << ans << '\n';
return 0;
}