我尝试构建Base 10到Base 2转换器......
var baseTen = window.prompt("Put a number from Base 10 to convert to base 2");
var baseTwo = [];
var num = baseTen;
var getBinary = function () {
baseTwo.reverse();
for (var i = 0; i <= baseTwo.length - 1; i++) {
document.write(baseTwo[i]);
}
};
var divide = function () {
while ( num > 0 ) {
if (num % 2 === 0) {
baseTwo.push(0);
num /= 2;
} else {
baseTwo.push(1);
num /= 2;
}
}
getBinary();
};
divide();
我遇到了一个问题......当我运行代码时,它打印出无穷无尽的“1”:\
我似乎无法在while循环中找到正确的条件,使其在“num”不能再分割的正确时间停止...它需要在达到零时停止。但我找不到办法做到这一点。将不胜感激。
答案 0 :(得分:2)
在这一行:
num /= 2;
你可能没有获得整数。 使用Math.floor:
num = Math.floor(num/2);
答案 1 :(得分:1)
我正在做Hacke-Rank 30天编码挑战,并且在10日问题有这个,转换问题。它是怎么回事。
// @author Tarandeep Singh :: Created recursive converter from base 10 to base 2
// @date : 2017-04-11
// Convert Base 10 to Base 2, We should reverse the output
// For Example base10to2(10) = "0101" just do res = base10to2(10).split('').reverse().join();
function base10to2(val, res = '') {
if (val >= 2) {
res += '' + val % 2;
return base10to2(val = Math.floor(val / 2), res);
} else {
res += '' + 1
return res;
}
}
// Well not needed in this case since we just want to count consecutive 1's but still :)
let n = 13;
var result = base10to2(n).split('').reverse().join();
document.write(`Converting ${n} into Base2 is ${result}`);
&#13;
在旁注中,您还可以使用toString方法来执行此操作。
像
let n = 13; console.log(n.toString(2));
这也有效。