Check if a numer is a power of 2 in ruby

The One imo not-so-obvious solution is:

# 0 -> false, 1->true, 2->true, 3->false ...
n.to_s(2).scan(/1/).size == 1

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:

n & (n – 1) == 0
... followed by ...
Math.log(n) / Math.log(2) % 1 == 0

5 thoughts on “Check if a numer is a power of 2 in ruby

  1. 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 🙂

  2. 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 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s