LeetCode: Add Binary Solution
Plus with remainderApproach
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)34 a = a.padStart(length, "0").split("").map(Number).reverse()5 b = b.padStart(length, "0").split("").map(Number).reverse()67 let res = []8 let remainder = 0910 for (let i = 0; i < length || remainder; i++) {11 let sum = (a[i] || 0) + (b[i] || 0) + remainder12 res.push(sum % 2)13 remainder = Math.floor(sum / 2)14 }1516 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