二进制加法

61 阅读1分钟
输入为 非空 字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
 */

var add = function(a, b) {
    let ret = [];
    let i = a.length - 1, j = b.length - 1;
    let carry = 0;
    while(a[i] || b[j]) {
        let ch1 = a[i] ? parseInt(a[i]) : 0;
        let ch2 = b[j] ? parseInt(b[j]) : 0;
        let sum = ch1 + ch2 + carry;
        carry = sum >= 2 ? 1 : 0;
        ret.unshift(sum % 2);
        i--;
        j--;
    }
    if (carry === 1) ret.unshift(1);
    return ret.join('');
}