1.十進制轉換爲二進制spa
var toBin = (n) => { if(n == 0) return '0'; var res = ''; while(n != 0) { res = n % 2 + res n = parseInt(n / 2) } return res; }
2.二進制轉換爲十進制code
var toDecimal = (s) => { var res = 0; var arr = s.split(''); var len = arr.length; for(var i = 0;i<len;i++) { res += +arr[i] * Math.pow(2, len-1-i) } return res; }
3.驗證blog
toBin和toDecimal應該爲互逆的
經過判斷 i == toDecimal(toBin(i)) 檢測0-100000是否準確ci
for(var i = 0;i<100000;i++) { if(i != toDecimal(toBin(i))) console.log(i); } console.log('end!')