Converting base-10 to base2 in Ruby using recursion (Binary converter) -
i convert base10 number base2 in ruby without using built in to_s(2) method, using recursion.
i wrote this:
def to_binary(d) if d<1 return "" else return to_binary(d/2).to_s + (d%2).to_s end end this return correct results except 0. there way return 0 0 without having leading zeroes numbers greater 0?
you can modify checks bit:
def to_binary(d) return d.to_s if [0,1].include?(d) # same "if d == 0 || d == 1" to_binary(d/2) + (d%2).to_s end to_binary(10) == "1010" #=> true to_binary(0) == "0" #=> true you write above method as:
def to_binary(d) return d.to_s if [0,1].include?(d) div,mod = d.divmod(2) to_binary(div) + mod.to_s end
Comments
Post a Comment