Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

67. Add Binary #228

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

67. Add Binary

给你两个二进制字符串,返回它们的和(用二进制表示)。

输入为 非空 字符串且只包含数字 10

Example 1

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

Example 2

Input: a = "1010", b = "1011"
Output: "10101"

Note

Tcdian commented 4 years ago

Solution

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
    const maxLen = a.length > b.length ? a.length + 1 : b.length + 1;
    const completedA = a.padStart(maxLen, '0');
    const completedB = b.padStart(maxLen, '0');
    let curry = 0;
    let result = '';
    for (let i = maxLen - 1; i >= 0; i--) {
        const sum = Number(completedA[i]) + Number(completedB[i]) + curry;
        result = String(sum % 2) + result;
        curry = sum >> 1;
    }
    let from = 0;
    while(from !== result.length - 1 && result[from] === '0') {
        from++;
    }
    return result.slice(from);
};
function addBinary(a: string, b: string): string {
    const maxLen = a.length > b.length ? a.length + 1 : b.length + 1;
    const completedA = a.padStart(maxLen, '0');
    const completedB = b.padStart(maxLen, '0');
    let curry = 0;
    let result = '';
    for (let i = maxLen - 1; i >= 0; i--) {
        const sum = Number(completedA[i]) + Number(completedB[i]) + curry;
        result = String(sum % 2) + result;
        curry = sum >> 1;
    }
    let from = 0;
    while(from !== result.length - 1 && result[from] === '0') {
        from++;
    }
    return result.slice(from);
};