diff --git a/leet-code/67-binary-add/README.md b/leet-code/67-binary-add/README.md new file mode 100644 index 0000000..d92a84a --- /dev/null +++ b/leet-code/67-binary-add/README.md @@ -0,0 +1,18 @@ +# 67-binary-add +Given two binary strings a and b, return their sum as a binary string. + +Example 1: + +Input: a = "11", b = "1" +Output: "100" +Example 2: + +Input: a = "1010", b = "1011" +Output: "10101" + + +Constraints: + +1 <= a.length, b.length <= 104 +a and b consist only of '0' or '1' characters. +Each string does not contain leading zeros except for the zero itself. \ No newline at end of file diff --git a/leet-code/67-binary-add/index.js b/leet-code/67-binary-add/index.js new file mode 100644 index 0000000..6282385 --- /dev/null +++ b/leet-code/67-binary-add/index.js @@ -0,0 +1,33 @@ +/** + * @param {string} a + * @param {string} b + * @return {string} + */ +var addBinary = function(a, b) { + // pointer for each bitstring + let i = a.length - 1; + let j = b.length - 1; + // store the carry value for each place value + let carry = 0 + // store the resulting bitstring + const result = [] + // continue as long as either input bitstring has digits remaining + while (i >= 0 || j >= 0) { + // read the next digit in each bitstring + const a1 = a[i] === '1' ? 1 : 0 + const b1 = b[j] === '1' ? 1 : 0 + // sum of digits + const sum = carry + a1 + b1 + // divide by 2 + carry = sum >> 1 + // remainder upon division by 2 + result.push(sum & 1) + // progress to next digit + i-- + j-- + } + // add left over carry as most significant digit + if (carry) result.push('1'); + // order most to least significant bits + return result.reverse().join(''); +}; \ No newline at end of file