Created
March 5, 2022 19:02
-
-
Save esase/056697fd64576497c53bac42c2c16555 to your computer and use it in GitHub Desktop.
Add binary [https://leetcode.com/problems/add-binary]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} a | |
* @param {string} b | |
* @return {string} | |
*/ | |
var addBinary = function(a, b) { | |
console.log(BigInt("0b"+a, 2) + BigInt("0b"+b, 2)); | |
// align strings | |
if (a.length !== b.length) { | |
a.length > b.length | |
? b = '0'.repeat(a.length - b.length) + b | |
: a = '0'.repeat(b.length - a.length) + a; | |
} | |
const sumMap = new Map(); | |
sumMap.set('00', 0); | |
sumMap.set('01', 1); | |
sumMap.set('10', 1); | |
sumMap.set('11', 10); | |
let rest = 0; | |
const result = []; | |
for (let i = a.length - 1; i >= 0; i--) { | |
let digit1 = a[i]; | |
let digit2 = b[i]; | |
if (rest) { | |
digit1 = sumMap.get(`${rest}${digit1}`); | |
rest = 0; | |
if (digit1 === 10) { | |
digit1 = 0; | |
rest = 1; | |
} | |
} | |
const sumResult = sumMap.get(`${digit1}${digit2}`); | |
if (sumResult == 10) { | |
result.push(0); | |
rest = 1; | |
continue; | |
} | |
result.push(sumResult); | |
} | |
if (rest) { | |
result.push(1); | |
} | |
return result.reverse().join(''); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment