In JS looks something like this.
const isIntegerPowerOfTwo = number =>
number > 0 && (number & (number - 1)) === 0;
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)
Sure, will update, thanks!
Surely any number is a power of 2?
Your code is checking for integer powers of 2
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)
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
Thanks, let it be