Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions leet-code/67-binary-add/README.md
Original file line number Diff line number Diff line change
@@ -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.
33 changes: 33 additions & 0 deletions leet-code/67-binary-add/index.js
Original file line number Diff line number Diff line change
@@ -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('');
};