美文网首页
67. Add Binary

67. Add Binary

作者: Icytail | 来源:发表于2017-11-09 00:29 被阅读0次

    Description:

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

    For example,
    a = "11"
    b = "1"
    Return "100".

    My code:

    /**
     * @param {string} a
     * @param {string} b
     * @return {string}
     */
    var addBinary = function(a, b) {
        // return parseInt((parseInt(a, 2) + parseInt(b, 2)).toString(2), 2).toString(2); 没有大整数精度处理
        let arrA = a.split(''), arrB = b.split(''), carry = 0, sum = 0, arrSum = [], temp = 0;
        while(arrA.length != 0 && arrB.length != 0) {
            temp = parseInt(arrA.pop()) + parseInt(arrB.pop()) + carry;
            arrSum.push(temp % 2);
            carry =parseInt(temp / 2);
        }
        while(arrA.length != 0) {
            temp = parseInt(arrA.pop()) + carry;
            arrSum.push(temp % 2);
            carry = parseInt(temp / 2);
        }
        while(arrB.length != 0) {
            temp = parseInt(arrB.pop()) + carry;
            arrSum.push(temp % 2);
            carry = parseInt(temp / 2);
        }
        if(arrA.length == 0 && arrB.length == 0 && carry) {
            arrSum.push(carry);
        }
        return arrSum.reverse().join('');
    };
    

    Note: 不能忘记类型转换

    相关文章

      网友评论

          本文标题:67. Add Binary

          本文链接:https://www.haomeiwen.com/subject/zsiumxtx.html