您的位置:首页 > 其它

Project Euler Problem 36 Double-base palindromes

2017-03-30 01:00 239 查看
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.)

C++(Simpler):
#include <iostream>

using namespace std;

const int N = 1000000;

bool ispalindrom(int n, int base)
{
int palindrom = 0, temp;

temp = n;
while(temp) {
palindrom *= base;
palindrom += temp % base;
temp /= base;
}

return n == palindrom;
}

int main()
{
long total = 0;

for(int i=1; i<N; i++) {
if(!ispalindrom(i, 10))
continue;

if(!ispalindrom(i, 2))
continue;

total += i;
}

cout << total << endl;

return 0;
}

C++:
#include <iostream>
#include <cstring>

using namespace std;

const int N = 1000000;

void myitoa(int n, char *p, int base)
{
while(n) {
*p++ = '0' + n % base;
n /= base;
}

*p = '\0';
}

bool ispalindrom(char s[])
{
int start = 0;
int end = strlen(s) - 1;

while(start < end) {
if(s[end] != s[start])
return false;
start++;
end--;

}

return true;
}

int main()
{
char s[32];
long total = 0;

for(int i=1; i<N; i++) {
myitoa(i, s, 10);
if(!ispalindrom(s))
continue;

myitoa(i, s, 2);
if(!ispalindrom(s))
continue;

total += i;
}

cout << total << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: