Skip to content

Instantly share code, notes, and snippets.

@lastday154
Created March 5, 2019 03:31
Show Gist options
  • Save lastday154/bf601255badbb0c2e6da590241695d33 to your computer and use it in GitHub Desktop.
Save lastday154/bf601255badbb0c2e6da590241695d33 to your computer and use it in GitHub Desktop.
binaryToInteger
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function binaryToInteger(A) {
let sum = 0;
for (let i = 0; i < A.length; i++) {
sum += A[i] * Math.pow(-2, i);
}
return sum;
}
function integerToNegativeBinary(n) {
const mask = 0xAAAAAAAA;
return ((n + mask) ^ mask).toString(2);
}
function solution(A, B) {
const a = binaryToInteger(A);
const b = binaryToInteger(B);
const sum = a + b;
const result = integerToNegativeBinary(sum).split("").reverse().map((item) => {
return parseInt(item);
})
return result;
}
console.log('solution: ', solution([0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment