Project Ruler 算法练习之 10 进制 转 2进制 以及数字对称

时间:2014-06-07 13:42:45   收藏:0   阅读:189

问题描述:

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


1.找出十进制对称的数字

2.在十进制对称的数字转2进制找出2进制也对称的数字


(function(){

var isPalin = function (n){
var strN = n.toString();
if(strN.length < 2)return false;

for(var i =0 ;i <= n/2;i++){if(strN[i] != strN[strN.length-1-i]) return false;}

return true;
};

var toBinary = function tb(n){
if(this.ret == undefined) this.ret = "";

var tmp = n / 2 | 0;
this.ret = (n % 2).toString() + this.ret;
if(tmp == 1){var r = "1" + this.ret; this.ret = ""; return r;}
else{return tb(tmp);}

};

for(var i = 1; i< 300 ;i ++){
if(isPalin(i) && isPalin(toBinary(i))) console.log (i);
}

})();


Project Ruler 算法练习之 10 进制 转 2进制 以及数字对称,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!