Ch Skilbeck wrote: > Hi, > > Can someone tell me if there's a better way to do this? It takes a > number and returns the next power of 2 up (or the original if it was > already a power of 2) Specifically, are there features of Ruby that I > should be using in this case? > > Cheers, > Charlie. > > def nextPowerOf2(n) > raise "integer please" if !n.kind_of? Integer > high = 0 > count = 0 > (0..n.size * 8 - 2).each {|b| count += n[b] ; high = b if n[b] != 0} > 1 << high + (count > 1 ? 1 : 0) > end 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 Kind regards robert