Created
March 5, 2019 03:31
-
-
Save lastday154/bf601255badbb0c2e6da590241695d33 to your computer and use it in GitHub Desktop.
binaryToInteger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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