DEV Community

Andrei Iatsuk
Andrei Iatsuk

Posted on β€’ Edited on

4 2

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
Andrei Iatsuk β€’

Sure, will update, thanks!

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ β€’ β€’ Edited

Surely any number is a power of 2?

2log⁑2x=x 2^{\log_2 x}=x

Your code is checking for integer powers of 2
Collapse
 
ytskk profile image
Andrei Iatsuk β€’ β€’ 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
Andrei Iatsuk β€’

Thanks, let it be

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay