DEV Community

Andrey
Andrey

Posted on • Edited on

How to check if a number is a power of two for O(1)

Image descriptionDart solution.

In JS looks something like this.

const isIntegerPowerOfTwo = number =>
    number > 0 && (number & (number - 1)) === 0;
Enter fullscreen mode Exit fullscreen mode

Thanks to Luke Shiru for code.

Explanation

In binary representation, numbers consist of 0 and 1. And it just so happens that all powers of two are 10*.
For example, 2 -> 10, 8 -> 1000, and so on.
When we do a comparison of number & number - 1 == 0, we check 100 & 011, which will always yield 0.

3 → 11. 3 & 2 => 11 & 10 = 1.

Top comments (5)

Collapse
 
ytskk profile image
Andrey

Sure, will update, thanks!

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Surely any number is a power of 2?

2log2x=x 2^{\log_2 x}=x

Your code is checking for integer powers of 2
Collapse
 
ytskk profile image
Andrey • Edited

Hello, dont correctly understand about log. It can be simplified to x = x, and?

This method only about integer power numbers, check the input number type.

If you could found way to work with float , let us know)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

The input number type does not tell you that this is checking for integer powers. To make the intent of your function clearer, it would be better named something like isIntegerPowOfTwo

Thread Thread
 
ytskk profile image
Andrey

Thanks, let it be