Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created July 19, 2020 07:22
Show Gist options
  • Save RP-3/c4d18279e7c1885c9adc88104cadea45 to your computer and use it in GitHub Desktop.
Save RP-3/c4d18279e7c1885c9adc88104cadea45 to your computer and use it in GitHub Desktop.
/*
Sort-of brute force... I know there's a cleverer way to
do this with XORs and bit tricks but if the answer doesn't
fit into 53-bit int I'd be hosed so I'm sticking to what
I know will work =P
O(max(a.length, b.length))
*/
var addBinary = function(a, b) {
const result = [];
const len = Math.max(a.length, b.length);
let i = 1;
let carry = 0;
while(len - i >= 0){
const x = a[a.length-i] === '1' ? 1 : 0;
const y = b[b.length-i] === '1' ? 1 : 0;
const sum = x + y + carry;
if(sum === 0){
result.push(0);
carry = 0;
}
else if(sum === 1){
result.push(1);
carry = 0;
}
else if(sum === 2){
result.push(0);
carry = 1;
}
else if(sum === 3){
result.push(1);
carry = 1;
}
i++;
}
if(carry) 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