Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. 'use strict';
  2.  
  3. function toDecimal(A) {
  4. var sum = 0;
  5. for (var i = 0; i < A.length; i++) {
  6. sum += A[i] * Math.pow(-2, i);
  7. }
  8. return sum;
  9. }
  10.  
  11. function toBaseNeg2(d) {
  12. var a = [];
  13. while (d != 0) {
  14. var remainder = d % -2;
  15. var d = Math.ceil(d / -2);
  16. a.push(Math.abs(remainder));
  17. }
  18. return a;
  19. }
  20.  
  21. function solution(A, B) {
  22. var d = toDecimal(A);
  23. return toBaseNeg2(-d);
  24. }
  25.  
  26. console.log(toDecimal([1,0,0,1,1]) === 9);
  27. console.log(toDecimal([1,1,0,1]) === -9);
  28. console.log(toDecimal([1,0,0,1,1,1]) === -23);
  29. console.log(toDecimal([1,1,0,1,0,1,1]) === 23);
  30.  
  31. console.log(JSON.stringify(toBaseNeg2(9)) == JSON.stringify([1,0,0,1,1]));
  32. console.log(JSON.stringify(toBaseNeg2(-9)) == JSON.stringify([1,1,0,1]));
  33. console.log(JSON.stringify(toBaseNeg2(-23)) == JSON.stringify([1,0,0,1,1,1]));
  34. console.log(JSON.stringify(toBaseNeg2(23)) == JSON.stringify([1,1,0,1,0,1,1]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement