码迷,mamicode.com
首页 > 其他好文 > 详细

Project Euler:Problem 36 Double-base palindromes

时间:2015-06-04 12:00:19      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:c++   project euler   

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


#include <iostream>
#include <string>
using namespace std;

string bin(int a)
{
	string res = "";
	while (a)
	{
		if (a % 2 == 1)
			res = '1' + res;
		else
			res = '0' + res;
		a /= 2;
	}
	return res;
}

bool pali_str(string  s)
{
	for (int i = 0; i < s.length() / 2; i++)
	{
		if (s[i] != s[s.length() - 1 - i])
			return false;
	}
	return true;
}

bool pali_int(int a)
{
	string s = "";
	while (a)
	{
		char c = a % 10 + '0';
		a /= 10;
		s = c + s;
	}
	if (pali_str(s))
		return true;
	else
		return false;
}



int main()
{
	int res = 0;
	for (int i = 1; i <= 1000000; i++)
	{
		if (pali_int(i) && pali_str(bin(i)))
			res += i;
	}
	cout << res << endl;
	system("pause");
	return 0;
}


Project Euler:Problem 36 Double-base palindromes

标签:c++   project euler   

原文地址:http://blog.csdn.net/youb11/article/details/46356413

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!