67. Add Binary

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: 不能忘记类型转换

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容