标签:c++ project euler
The decimal number, 585 = 10010010012 (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 <iostream> #include <string> using namespace std; string bin(int a) { string res = ""; while (a) { if (a % 2 == 1) res = '1' + res; else res = '0' + res; a /= 2; } return res; } bool pali_str(string s) { for (int i = 0; i < s.length() / 2; i++) { if (s[i] != s[s.length() - 1 - i]) return false; } return true; } bool pali_int(int a) { string s = ""; while (a) { char c = a % 10 + '0'; a /= 10; s = c + s; } if (pali_str(s)) return true; else return false; } int main() { int res = 0; for (int i = 1; i <= 1000000; i++) { if (pali_int(i) && pali_str(bin(i))) res += i; } cout << res << endl; system("pause"); return 0; }
Project Euler:Problem 36 Double-base palindromes
标签:c++ project euler
原文地址:http://blog.csdn.net/youb11/article/details/46356413