Yagiz
Yagiz

Reputation: 1033

-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?

Upvotes: 1

Views: 478

Answers (1)

Shelvacu
Shelvacu

Reputation: 4360

Adapted from Mark Dickinson's comment:

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

Upvotes: 2

Related Questions