欧拉计划36题

/**
* 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.)
*
求1000000以内10进制数和它的2进制数都是回文数的和

分析
第一反应,循环所有的数,依次做判断,并求和
因为2进制回文,可得出最后一位一定是1,即该数是奇数
因此只需判断所有奇数,减少一半计算量
本题的难点在于十进制与二进制的转换
使用不断除二,余数倒置的方法求2二进制
如 21
22 / 2 = 11 ...0
11 / 2 = 5  ...1
5  / 2 = 2  ...1
2  / 2 = 1  ...0
1  / 2 = 0  ...1
所以22的二进制表示为10110

代码实现:
String result = "";
while (!"1".equals(decimal)){

if (isOdd(decimal)){
result = "1" + result;
} else {
result = "0" + result;
}
int c = 0;
String temp = "";
for (int i = 0; i < decimal.length(); i++){
int a = new Integer("" + c + decimal.charAt(i));
if (a == 1 && i == 0) {
c = 1;
continue;
}

temp = temp + a / 2;

if (a % 2 == 1){
c = 1;
} else {
c = 0;
}
}
decimal = temp;

}
return "1" + result;

结果:872187






















猜你喜欢

转载自535260620.iteye.com/blog/2284441