mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Add isPowerOfTwo function.
This commit is contained in:
@@ -91,23 +91,6 @@ inverting all of the bits of the number and adding 1 to it.
|
||||
|
||||
> See [switchSign.js](switchSign.js) for further details.
|
||||
|
||||
#### Power of 2
|
||||
|
||||
This method checks if a number provided is power of two. It uses the property that when
|
||||
a power of 2 is `&` with power of 2 minus 1, it would return 0 implying that the provided
|
||||
number is power of 2.
|
||||
|
||||
```
|
||||
Number: 4
|
||||
Power of 2: True
|
||||
|
||||
Number: 1
|
||||
Power of 2: False
|
||||
```
|
||||
|
||||
> See `ifPowerof2` function for further details.
|
||||
|
||||
|
||||
#### Multiply Two Numbers
|
||||
|
||||
This method multiplies two integer numbers using bitwise operators.
|
||||
@@ -173,6 +156,24 @@ When we shift 1 four times it will become bigger than 5.
|
||||
|
||||
> See [bitLength.js](bitLength.js) for further details.
|
||||
|
||||
#### Is Power of Two
|
||||
|
||||
This method checks if a number provided is power of two. It uses the following
|
||||
property. Let's say that `powerNumber` is a number that has been formed as a power
|
||||
of two (i.e. 2, 4, 8, 16 etc.). Then if we'll do `&` operation between `powerNumber`
|
||||
and `powerNumber - 1` it will return `0` (in case if number is power of two).
|
||||
|
||||
```
|
||||
Number: 4 = 0b0100
|
||||
Number: 3 = (4 - 1) = 0b0011
|
||||
4 & 3 = 0b0100 & 0b0011 = 0b0000 <-- Equal to zero, is power of two.
|
||||
|
||||
Number: 10 = 0b01010
|
||||
Number: 9 = (10 - 1) = 0b01001
|
||||
10 & 9 = 0b01010 & 0b01001 = 0b01000 <-- Not equal to zero, not a power of two.
|
||||
```
|
||||
|
||||
> See [isPowerOfTwo.js](isPowerOfTwo.js) for further details.
|
||||
|
||||
## References
|
||||
|
||||
|
||||
Reference in New Issue
Block a user