JavaScript(添加二进制)

hon*_*boy 1 javascript binary

这是提示:

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"
Example 2:

Input: a = "1010", b = "1011"
Output: "10101"
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

var addBinary = function(a, b) {
    var c = (Number(a) + Number(b)).toString();
    var binaryTotal = "";
    var temp = 0;
    for (var i=c.length - 1; i>=0; i--) {
        console.log(temp, 'temp')
        console.log(c[i], 'c[i]')
        c[i] = (temp + Number(c[i])).toString();
        console.log(c[i], 'after')
        if (c[i] === '3') {
            binaryTotal = '1' + binaryTotal;
            temp = 1;
        } else if (c[i] === '2') {
            binaryTotal = '0' + binaryTotal;
            temp = 1;
        } else if (c[i] === '1') {
            binaryTotal = '1' + binaryTotal;
            temp = 0;
        } else if (c[i] === '0') {
            binaryTotal = '0' + binaryTotal;
            temp = 0;
        }
        if (temp === 1 && i === 0) {
            binaryTotal = '1' + binaryTotal;
        }
        console.log(binaryTotal, 'binaryTotal')
    }
    return binaryTotal;
};
Run Code Online (Sandbox Code Playgroud)

如果我用输入进行测试a = "11", b = "1",我的输出就会显示"10",但我在期待"100"。我认为我的这部分代码有问题c[i] = (temp + Number(c[i])).toString();,但我不明白出了什么问题。我期望c[1]等于2equals i0但我没有得到。我尝试切换NumberparseInt得到相同的结果。有人可以解释一下吗?

这是标准输出的结果:

0 temp
2 c[i]
2 after
0 binaryTotal
1 temp
1 c[i]
1 after
10 binaryTotal
Run Code Online (Sandbox Code Playgroud)

Tou*_*ffy 6

这是一个懒惰的答案:

function addBinary(a, b) {
  return (parseInt(a, 2) + parseInt(b, 2)).toString(2)
}
Run Code Online (Sandbox Code Playgroud)

这是具有无限精度的懒惰答案:

function addBigBinary(a, b) {
  return (BigInt('0b'+a) + BigInt('0b'+b)).toString(2)
}
Run Code Online (Sandbox Code Playgroud)