From: ara.t.howard@... Date: 2006-08-08T01:21:40+09:00 Subject: Re: nextPowerOf2(n) On Tue, 8 Aug 2006, Alex Young wrote: > Robert Klemme wrote: > >> Did we have this solution already? >> >> class Integer >> def next_power >> x = self >> c = 0 >> >> until x == 0 >> x >>= 1 >> c += 1 >> end >> >> 1 << c >> end >> end > Neat, but hits an infinite loop for negative x. Then again, that wasn't part > of the original problem... easy to fix: harp:~ > cat a.rb class Integer def next_power_2 return @next_power_2 if defined? @next_power_2 x = self.abs c = 0 until x == 0 x >>= 1 c += 1 end np2 = 1 << c @next_power_2 = self < 0 ? -np2 : np2 end end p 42.next_power_2 p -42.next_power_2 harp:~ > ruby a.rb 64 -64 note that it's 'vectorized' : positives move up and negatives down. -a -- to foster inner awareness, introspection, and reasoning is more efficient than meditation and prayer. - h.h. the 14th dali lama