Skip to content

Instantly share code, notes, and snippets.

@edev90
Created April 1, 2024 19:39
Show Gist options
  • Save edev90/93fb814b4de2d15129530f4e1e2cf412 to your computer and use it in GitHub Desktop.
Save edev90/93fb814b4de2d15129530f4e1e2cf412 to your computer and use it in GitHub Desktop.
Adds two binary strings in JavaScript and returns sum string
var addBinary = function(a, b) {
let aLen = a.length, bLen = b.length;
let maxLen = aLen;
if(bLen > aLen) {
maxLen = bLen;
}
let carryBit = 0;
let sumStr = "";
for(let i = 1; i <= maxLen || carryBit > 0; i++) {
let bitA = 0, bitB = 0;
let aOffset = aLen - i;
let bOffset = bLen - i;
if(aOffset >= 0 && a[aOffset] == '1') {
bitA = 1;
}
if(bOffset >= 0 && b[bOffset] == '1') {
bitB = 1;
}
let sum = carryBit + bitA + bitB;
if((sum & 1) == 0) {
sumStr = "0" + sumStr;
} else {
sumStr = "1" + sumStr;
}
carryBit = sum >> 1;
}
return sumStr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment