我试着建造一个基地10到基地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();我有一个问题,though...when,我运行它打印的无限的"1"s :\
我似乎无法在while循环中找到正确的条件,使其在"num“不能被除以的正确时间停止,当达到零时,anymore...it需要停止。但我想不出办法。我们会感谢你的帮助。
发布于 2014-01-25 16:57:55
在这一行:
num /= 2;你可能没有得到整数。使用Math.floor:
num = Math.floor(num/2);发布于 2017-04-12 16:49:14
Javascript中base10到base2转换的清洁递归方法
我在做Hacke 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}`);
另外,您还可以使用数字的toString方法来完成此操作。
就像let n = 13; console.log(n.toString(2));一样,这也是可行的。
https://stackoverflow.com/questions/21353330
复制相似问题