-
-
Save Noitidart/ab07b1bfb4945065a8181d3dafeb0916 to your computer and use it in GitHub Desktop.
Toptal Codility Problem: Convert to-and-from base -2
This file contains hidden or 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
'use strict'; | |
function toDecimal(A) { | |
var sum = 0; | |
for (var i = 0; i < A.length; i++) { | |
sum += A[i] * Math.pow(-2, i); | |
} | |
return sum; | |
} | |
function toBaseNeg2(d) { | |
var a = []; | |
while (d != 0) { | |
var remainder = d % -2; | |
var d = Math.ceil(d / -2); | |
a.push(Math.abs(remainder)); | |
} | |
return a; | |
} | |
function solution(A, B) { | |
var d = toDecimal(A); | |
return toBaseNeg2(-d); | |
} | |
console.log(toDecimal([1,0,0,1,1]) === 9); | |
console.log(toDecimal([1,1,0,1]) === -9); | |
console.log(toDecimal([1,0,0,1,1,1]) === -23); | |
console.log(toDecimal([1,1,0,1,0,1,1]) === 23); | |
console.log(JSON.stringify(toBaseNeg2(9)) == JSON.stringify([1,0,0,1,1])); | |
console.log(JSON.stringify(toBaseNeg2(-9)) == JSON.stringify([1,1,0,1])); | |
console.log(JSON.stringify(toBaseNeg2(-23)) == JSON.stringify([1,0,0,1,1,1])); | |
console.log(JSON.stringify(toBaseNeg2(23)) == JSON.stringify([1,1,0,1,0,1,1])); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment