From: William James Date: 2009-02-11T10:03:53+09:00 Subject: Re: how to do the recursion Li Chen wrote: > Hi all, > > In order to study recursion, I want to change a decimal number into a > binary number based on the algorithm on website > > http://www.trunix.org/programlama/cpp/fred/notes/cpp/misc/decimal2bina > ry.html > > But my codes don't work. Any idea or optimization? > > Thanks, > > Li > > > ############### > def decimal_to_binary(number) > > dec=number > results=[] > > if dec==0 ||dec==1 > results<< dec > else > > mode=dec%2 > if mode==1# this is an odd number > results<<1 > dec=(dec-1)/2 > elsif mode==0 #this is an even number > results<<0 > dec=dec/2 > results<<1 if dec==1# if number is 2 > end > end > > decimal_to_binary(dec) if dec>1 > p results.reverse > > end > > > ############## > decimal_to_binary(3) If you found Pascal's code somewhat puzzling, let me explain. His customary language is CLisp, so when he deigns to dabble in Ruby, he tries to make his code look lispish. def dec_to_binary num, result = [] result << if num.odd? 1 else 0 end if num < 2 result.reverse.join "" else dec_to_binary num/2, result end end p dec_to_binary 254