Project Euler Problem 36 Double-base palindromes

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;
}



posted on 2017-03-30 01:00  海岛Blog  阅读(236)  评论(0编辑  收藏  举报

导航