Skip to content

Commit 70b0e0a

Browse files
tapaswenipathaktrekhleb
authored andcommitted
Add ifPowerOf2c (trekhleb#155)
1 parent 20497bb commit 70b0e0a

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

src/algorithms/math/bits/README.md

+18
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,23 @@ inverting all of the bits of the number and adding 1 to it.
9191

9292
> See [switchSign.js](switchSign.js) for further details.
9393
94+
#### Power of 2
95+
96+
This method checks if a number provided is power of two. It uses the property that when
97+
a power of 2 is `&` with power of 2 minus 1, it would return 0 implying that the provided
98+
number is power of 2.
99+
100+
```
101+
Number: 4
102+
Power of 2: True
103+
104+
Number: 1
105+
Power of 2: False
106+
```
107+
108+
> See `ifPowerof2` function for further details.
109+
110+
94111
#### Multiply Two Numbers
95112

96113
This method multiplies two integer numbers using bitwise operators.
@@ -156,6 +173,7 @@ When we shift 1 four times it will become bigger than 5.
156173

157174
> See [bitLength.js](bitLength.js) for further details.
158175
176+
159177
## References
160178

161179
- [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import ifPowerOf2 from '../ifPowerOf2';
2+
3+
describe('ifPowerOf2', () => {
4+
it('Should return if the number is power of 2 or not', () => {
5+
expect(ifPowerOf2(5)).toBe(false);
6+
expect(ifPowerOf2(4)).toBe(true);
7+
});
8+
});
+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/**
2+
* @param {number} number
3+
* @return bool
4+
*/
5+
export default function ifPowerOf2(number) {
6+
return number && (!(number & (number - 1)));
7+
}

0 commit comments

Comments
 (0)