欧拉计划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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值