js二进制求和

二进制求和

示例 1:
输入: a = "11", b = "1" 输出: "100"
示例 2:
输入: a = "1010", b = "1011" 输出: "10101"
提示:

  • 每个字符串仅由字符01组成。

  • 1 <= a.length, b.length <= 10^4

  • 字符串如果不是0,就都不含前导零

    上代码

 /**
     * @param {string} a
     * @param {string} b
     * @return {string}
     */
    var addBinary = function(a, b) {
        let res = '';
        let c = 0;
        a = a.split('');
        b = b.split('');
        while(a.length||b.length||c){
            c += ~~a.pop() + ~~b.pop();
            res = c%2+res;
            c = c>1
        }
        return res
    };
    console.log(addBinary("11","1"))//100
    console.log(addBinary("1010","1011"))//10101

你可能感兴趣的:(原生JavaScript,javascript)