我希望看到二进制形式的正整数或负整数。
很像这个问题,但是是针对JavaScript的。
我希望看到二进制形式的正整数或负整数。
很像这个问题,但是是针对JavaScript的。
当前回答
我们还可以计算正数或负数的二进制,如下所示:
函数toBinary (n) { Let binary = ""; 如果(n < 0) { N = N >>> 0; } while(Math.ceil(n/2) > 0){ 二进制= n%2 +二进制; n = Math.floor(n/2); } 返回二进制; } console.log (toBinary (7)); console.log (toBinary (7));
其他回答
还有一个选择
const decToBin = dec => {
let bin = '';
let f = false;
while (!f) {
bin = bin + (dec % 2);
dec = Math.trunc(dec / 2);
if (dec === 0 ) f = true;
}
return bin.split("").reverse().join("");
}
console.log(decToBin(0));
console.log(decToBin(1));
console.log(decToBin(2));
console.log(decToBin(3));
console.log(decToBin(4));
console.log(decToBin(5));
console.log(decToBin(6));
这就是解。事实上,这很简单
function binaries(num1){
var str = num1.toString(2)
return(console.log('The binary form of ' + num1 + ' is: ' + str))
}
binaries(3
)
/*
According to MDN, Number.prototype.toString() overrides
Object.prototype.toString() with the useful distinction that you can
pass in a single integer argument. This argument is an optional radix,
numbers 2 to 36 allowed.So in the example above, we’re passing in 2 to
get a string representation of the binary for the base 10 number 100,
i.e. 1100100.
*/
您可以编写自己的函数来返回一个比特数组。 示例如何将数字转换为比特
除数|被除数|位/余数
2 | | 1
2 4 | | 0
2 | 2 | 0
~ | | ~ 1
上面一行的例子:2 * 4 = 8,余数为1 9 = 1 0 0 1
function numToBit(num){
var number = num
var result = []
while(number >= 1 ){
result.unshift(Math.floor(number%2))
number = number/2
}
return result
}
从下往上读余数。数字1从中间到上面。
你可以使用递归解决方案:
函数intToBinary(number, res = "") { If (number < 1) If (res === "")返回"0" 其他的 返回res 否则返回intToBinary(数学。楼层(数目/ 2),数目% 2 + res) } console.log (intToBinary (12)) console.log (intToBinary (546)) console.log (intToBinary (0)) console.log (intToBinary (125)) 只对正数有效。
逻辑可以被任何编程语言实现的实际解决方案:
如果你确定它只是积极的:
var a = 0;
var n = 12; // your input
var m = 1;
while(n) {
a = a + n%2*m;
n = Math.floor(n/2);
m = m*10;
}
console.log(n, ':', a) // 12 : 1100
若能负或正——
(n >>> 0).toString(2)