Skip to content

Instantly share code, notes, and snippets.

@adamloving
Created February 8, 2016 21:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adamloving/ebbeafc9dc1e773c7f90 to your computer and use it in GitHub Desktop.
Save adamloving/ebbeafc9dc1e773c7f90 to your computer and use it in GitHub Desktop.
Toptal Codility Problem: Convert to-and-from base -2
'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]));
@adamloving
Copy link
Author

A couple realizations while writing this:

  1. I should've written toDecimal() first to at least get partial credit (since the way I did it requires going to decimal and back - not sure if that's necessary).
  2. I was using Math.floor instead of Math.ceil - giving me incorrect results.

@adamloving
Copy link
Author

Here's the original problem...
77cb62ed-a32f-4d16-9d0f-38240f4f57c4

@u3k
Copy link

u3k commented Nov 20, 2016

unfortunately this will not satisfy the requirements. JS can only hold up to 2^53 in Number yet problem description states that number can be as big as 2^100000...

@kabiridris
Copy link

This solution seems to be correct. I recently solved it with 86% score because of some corner cases that I couldn't nail.

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