# 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. Reto says:

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. Reto says:

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

π

3. 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 π

4. Wow, actually readable and fast, its not very intuitive, but makes sense when you think about it π

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

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