工学1号馆

home

« | 返回首页 | »

Project Euler 36–Double-base palindromes

By Wu Yudong on August 20, 2018

Double-base palindromes

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.)


双进制回文数

十进制数585 = 10010010012(二进制表示),因此它在这两种进制下都是回文数。

找出所有小于一百万,且在十进制和二进制下均回文的数,并求它们的和。

(请注意,无论在哪种进制下,回文数均不考虑前导零。)

//(Problem 36)Double-base palindromes
// Completed on Thu, 31 Oct 2013, 13:12
// Language: C
//
// 版权所有(C)wu yudong 
// 博客地址:http://www.wuyudong.com

#include<stdio.h>
#include<stdbool.h>

bool test(int *a, int n)
{
	bool flag = true;
	for (int i = 0; i < n / 2; i++) {
		if (a[i] != a[n - i - 1]) {
			flag = false;
			break;
		}
	}
	return flag;
}

bool palindromes(int n, int base) //判断整数n在基为base时是否为回文数
{
	int a[100];
	int i = 0;
	while (n) {
		a[i++] = n % base;
		n /= base;
	}
	return test(a, i);
}

int main(void)
{
	int sum = 0;
	for (int i = 1; i <= 1000000; i += 2) {
		if (palindromes(i, 10) && palindromes(i, 2))
			sum += i;
	}
	printf("%d\n", sum);
	return 0;
}
Answer:872187
Completed on Thu, 31 Oct 2013, 21:12

如果文章对您有帮助,欢迎点击下方按钮打赏作者

Comments

No comments yet.
To verify that you are human, please fill in "七"(required)