Skip to content

Instantly share code, notes, and snippets.

@jeanmw
Last active August 15, 2020 14:56
Show Gist options
  • Save jeanmw/0871e1d3e3b0beb1509827202d5a630b to your computer and use it in GitHub Desktop.
Save jeanmw/0871e1d3e3b0beb1509827202d5a630b to your computer and use it in GitHub Desktop.
js function to add two binary number strings
function addTwoBinaries(a,b) {
///we need to track the carry value
//we also need to track the sum which will the be result
let carry = 0;
let result = "";
//we will need to do the add and carry operation at least as many times as the
//longest number, so let's keep track of two lengths for iteration
let i = 0;
let j = 0;
//while we have digits left on each, lets do the sum and carry
while(i<=a.length - 1 || j <=b.length-1) {
//magic
let num1 = i < 0 ? 0 : a[i] | 0;
let num2 = j < 0 ? 0 : b[j] | 0;
carry += num1 + num2; // sum of the two single digits
result = carry % 2 + result; //concat string in proper order
carry = carry / 2 | 0; // remove fractionals
i++;
j++;
}
//what if afterwards there is still carry leftover?
//if we still have a carry??
if(carry) {
result = carry + result;
}
return result;
}
console.log(addTwoBinaries("1101", "1001"));
@always186
Copy link

wrong with addTwoBinaries("100011", "1")

@sundaramj
Copy link

sundaramj commented Aug 15, 2020

yes its coming wrong as well for addTwoBinaries("11011","1000"), but ya well try.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment