Created
May 27, 2014 05:25
-
-
Save mouse-reeve/feeafe664f5c2b8fdfdc to your computer and use it in GitHub Desktop.
Converts a number to a negative base (between -2 and -10). Negadecimal, for example, or negabinary. http://en.wikipedia.org/wiki/Negative_base
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
function toNegativeBase(number, radix) { | |
if (radix > -2 || radix < -10) { | |
throw 'invalid radix'; | |
} | |
var result = 0; | |
while (number != 0) { | |
var exp = number > 0 ? 0 : 1; | |
var sum = 0; | |
while (Math.abs(sum) < Math.abs(number)) { | |
sum += (-radix-1) * Math.pow(radix, exp); | |
exp += 2; | |
} | |
exp -= 2; | |
var digit = Math.floor(number/Math.pow(radix, exp)); | |
digit = digit ? digit : 1; | |
number -= digit * Math.pow(radix, exp); | |
result += digit * Math.pow(10, exp); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment