Double-base palindromes
Problem 36
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.)
Answer: | 872187 |
Completed on Sat, 29 Oct 2016, 15:02 |
代码:
#include <iostream>
#include <cstring>
#include <sstream>
using namespace std;
string dectobin(long long a) //十进制转换成二进制
{
stringstream bin;
while(a!=0)
{
bin<<a%2;
a=a/2;
}
string binary;
bin>>binary;
return binary;
}
bool isPalindrome(string a) //判断是否回文
{
for(int i=0;i<a.length();i++)
{
if(a[i]!=a[a.length()-1-i])
return false;
}
return true;
}
int main()
{
long long int sum=0;
for(int i=1;i<1000000;i+=2)
{
stringstream a;
a<<i;
if(isPalindrome(a.str()))
{
string binary=dectobin(i);
if(isPalindrome(binary))
{
sum+=i;
cout<<i<<" "<<binary<<endl;
}
}
}
cout<<sum;
return 0;
}