From: Christer Nilsson Date: 2006-06-04T07:39:09+09:00 Subject: Re: Where can one find examples of masterful Ruby code? Logan Capaldo wrote: > On Jun 3, 2006, at 4:48 PM, Alder Green wrote: > >> For example: check if integer i is a power of 2, with an expression no >> more than 13 characters long. >> >> Solution: (i & (i - 1)) > > I'm confused. > > > irb(main):001:0> i = 9 > => 9 > irb(main):002:0> (i & (i - 1)) > => 8 > > So 9 is a power of 2? > > As far as 13 characters goes > > (i % 2).zero? > > is _exactly_ 13 characters and it gives a true or false answer > instead of zero of something else. Actually you have to compare with zero to get the expected result as a previous poster posted: def powerof2?( i ) (i&(i-1))==0 end (i&(i-1))==0 counts to twelve characters. i%2 determines odd or even. powerof2?(9) => false powerof2?(16) => true /christer -- Posted via http://www.ruby-forum.com/.