~~The~~ One imo not-so-obvious solution is:

And why it works is an exercise for the reader 😉

**Update:**

A crazy benchmark comparing different versions of power of 2 algorithms by reto

The fastest, still readable versions is:

Advertisements

~~The~~ One imo not-so-obvious solution is:

And why it works is an exercise for the reader 😉

**Update:**

A crazy benchmark comparing different versions of power of 2 algorithms by reto

The fastest, still readable versions is:

Advertisements

%d bloggers like this:

arggh 🙂

Math.log(n)/Math.log(2) % 1 == 0

=> does not convert a number to a binary string representation

=> does not compile a regexp

=> does not create a array of 1’s

=> does not count them 🙂

probably something with bit arithmetic is still faster than the log 🙂

or what about

n.to_s(2).match(/^10*$/)

🙂

I have something even faster (and are hellish proud of it):

def ispow2(n)

n & (n – 1) == 0

end

runs twice as fast as anything 😉

Wow, actually readable and fast, its not very intuitive, but makes sense when you think about it 🙂

(0..n).map {|i|n[i]}.inject(:+) == 1

That’s a somewhat obscure and fairly inefficient way to do it.