Created
March 17, 2016 22:46
-
-
Save arthurchui/92e356a4ace258ab1dc9 to your computer and use it in GitHub Desktop.
Get negative-base number from an integer
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
# Returns an array which index [0] represents the least significant bit. | |
# to_negativebase(9) # => [1, 0, 0, 1, 1] | |
# to_negativebase(-9) # => [1, 1, 0, 1] | |
def to_negativebase(value, base = -2) | |
raise ArgumentError if base > -2 | |
digits = [] | |
while value != 0 | |
value, mod = value.divmod(base) | |
if mod < 0 | |
mod += -base | |
value += 1 | |
end | |
digits << mod | |
end | |
digits | |
end | |
# Converts a r-based number to an integer. | |
# The array[0] represents the least significant bit. | |
def to_int(a, base = -2) | |
a.each_with_index.inject(0) { |result, (n, i)| result + n * (base ** i) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment