Project Euler Problem 36 Double-base palindromes

本文介绍了一种算法,用于寻找并计算所有小于一百万且在十进制和二进制下均为回文数的整数之和。提供了两种C++实现方案,一种采用简单的进制转换和比较,另一种则利用字符数组进行中间处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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



转载于:https://www.cnblogs.com/tigerisland/p/7563991.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值