Yagiz Yagiz - 2 months ago 21
Ruby Question

-2 base conversion algorithm suggestion

I am trying to convert an integer to base -2, but in Ruby

.to_s(-2)
doesn't get accepted. Do you have any other solutions to convert a number to -2 base?

Answer

Adapted from Mark Dickinson's comment:

def negabinary(n)
  return negabinary(-(n>>1)) + (n & 1).to_s if n != 0
  return ''
end