Skip to content

Instantly share code, notes, and snippets.

@wjramos
Created July 20, 2017 20:16
Show Gist options
  • Save wjramos/b78e722d24ed04c7ad6c0265ddd28648 to your computer and use it in GitHub Desktop.
Save wjramos/b78e722d24ed04c7ad6c0265ddd28648 to your computer and use it in GitHub Desktop.
bitCounter
function addBinary( strA, strB ) {
let result = '';
let carry = false;
for ( let i = Math.max( strA.length, strB.length ); i > -1; i-- ) {
result += addBits( strA[ i ] ? parseInt( strA[ i ] ) : 0, strB[ i ] ? parseInt( strB[ i ] ) : 0 );
}
return result;
function addBits( bitA = 0, bitB = 0 ) {
if ( ( carry && ( ( bitA && bitB ) || ( !bitA && !bitB ) ) ) || ( ( bitA || bitB ) && ( !bitA || !bitB ) ) ) {
return '1';
}
carry = ( bitA && bitB ) || ( carry && ( bitA || bitB ) );
return '0';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment