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...

Tags

leetcode

math

string

bit manipulation

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

CSSBattle 1.11: Eye of Sauron

Pseudo-element, half circle

Previous Post

LeetCode: Maximum Subarray

A classic DP problem

HoningJS

Search Posts