// Problem 36
// 31 January 2003
//
// 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 <windows.h>
using namespace std;
// 判斷是否爲迴文數,num爲字符串格式
bool IsPalindromicNum(char *numStr)
{
int length = strlen(numStr);
for(int i = length / 2 - 1; i >= 0; i--)
{
if(numStr[i] != numStr[length - i - 1])
{
return false;
}
}
return true;
}
void F1()
{
cout << "void F1()" << endl;
LARGE_INTEGER timeStart, timeEnd, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&timeStart);
const int MAX_NUM = 1000000;
const int MAX_LENGTH_BASE_2 = 21;
const int MAX_LENGTH_BASE_10 = 7;
char strBase10[MAX_LENGTH_BASE_10] = {0}; //保存10進制數的字符串形式,最大的數爲6位
char strBase2[MAX_LENGTH_BASE_2] = {0}; //保存2進制數的字符串形式,最大的數位20位
int sum = 0; //保存和
for(int i = 0; i < MAX_NUM; i++)
{
_itoa_s(i, strBase10, MAX_LENGTH_BASE_10, 10);
_itoa_s(i, strBase2, MAX_LENGTH_BASE_2, 2);
if(IsPalindromicNum(strBase10) && IsPalindromicNum(strBase2)) //如果10進制數和2進制數都是迴文數,10進制數放前面是因爲10進制數的位數較少
{
cout << i << ":" << strBase2 << endl;
sum += i;
}
}
cout << "總和爲" << sum << endl;
QueryPerformanceCounter(&timeEnd);
cout << "Total Milliseconds is " << (double)(timeEnd.QuadPart - timeStart.QuadPart) * 1000 / freq.QuadPart << endl;
}
//主函數
int main()
{
F1();
return 0;
}
/*
void F1()
0:0
1:1
3:11
5:101
7:111
9:1001
33:100001
99:1100011
313:100111001
585:1001001001
717:1011001101
7447:1110100010111
9009:10001100110001
15351:11101111110111
32223:111110111011111
39993:1001110000111001
53235:1100111111110011
53835:1101001001001011
73737:10010000000001001
585585:10001110111101110001
總和爲872187
Total Milliseconds is 1124.36
By GodMoon
2011年11月5日13:12:15
*/
【ProjectEuler】ProjectEuler_036
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.