LeetCode: Add Binary Solution

Plus with remainder

Approach

Plus each bit from right to left with remainder

Reverse the bit array so that we could do that from right to left

Implementation

1var addBinary = function (a, b) {
2 let length = Math.max(a.length, b.length)
3
4 a = a.padStart(length, "0").split("").map(Number).reverse()
5 b = b.padStart(length, "0").split("").map(Number).reverse()
6
7 let res = []
8 let remainder = 0
9
10 for (let i = 0; i < length || remainder; i++) {
11 let sum = (a[i] || 0) + (b[i] || 0) + remainder
12 res.push(sum % 2)
13 remainder = Math.floor(sum / 2)
14 }
15
16 return res.reverse().join("")
17}

Comments

Loading comments...

Next Post

CSSBattle 1.11: Eye of Sauron

Pseudo-element, half circle

Previous Post

LeetCode: Maximum Subarray

A classic DP problem