-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprojectEuler036.cpp
More file actions
65 lines (51 loc) · 1.21 KB
/
Copy pathprojectEuler036.cpp
File metadata and controls
65 lines (51 loc) · 1.21 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
61
62
63
64
65
/* Problem 36
Double-base Palindromes
The decimal number 585 = 1001001001 (binary) is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic
in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include
leading zeros.)
*/
#include <bitset>
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome (int x) {
string s = to_string (x);
while (s.length () > 1) {
if (s [0] != s [s.length () - 1]) {
return false;
} else {
s.erase (s.begin ());
s.erase (s.end () - 1);
}
}
return true;
}
bool isBinaryPalindrome (string s) {
while (s.length () > 1) {
if (s [0] != s [s.length () - 1]) {
return false;
} else {
s.erase (s.begin ());
s.erase (s.end () - 1);
}
}
return true;
}
int main () {
int sumPals = 0;
for (int i = 1; i < 1000000; i++) {
if (isPalindrome (i)) {
string binary = bitset<32> (i).to_string ();
while (binary [0] == '0') {
binary.erase (binary.begin ());
}
if (isBinaryPalindrome (binary)) {
cout << i << " " << binary << endl;
sumPals += i;
}
}
}
cout << sumPals << endl;
}