Skip to content

Commit d8fc33a

Browse files
dev-madhurendramadhuredra
andauthored
feat: added is power of two in bit manipulation (TheAlgorithms#157)
* feat : added is power of two in bit manipulation * fix : file name fixed --------- Co-authored-by: madhuredra <[email protected]>
1 parent f14c930 commit d8fc33a

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

bit_manipulation/is_power_of_2.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* This code will check whether the given number is a power of two or not.
3+
* @author dev-madhurendra<https://github.com/dev-madhurendra>
4+
* @explanation
5+
6+
A number will be a power of two if only one bit is set and rest are unset.
7+
This is true for all the cases except 01 because (2^0 = 1) which is not a power of 2.
8+
For eg: 10 (2^1 = 2), 100 (2^2 = 4), 10000 (2^4 = 16)
9+
10+
@see: https://www.hackerearth.com/practice/notes/round-a-number-to-the-next-power-of-2/
11+
12+
If we will subtract 1 from a number that is a power of 2 we will get it's
13+
1's complement.And we know that 1's complement is just opp. of that number.
14+
So, (n & (n-1)) will be 0.
15+
16+
For eg: (1000 & (1000-1))
17+
1 0 0 0 // Original Number (8)
18+
0 1 1 1 // After Subtracting 1 (8-1 = 7)
19+
_______
20+
0 0 0 0 // will become 0
21+
* @param {number}
22+
* @returns {boolean}
23+
*/
24+
25+
export const isPowerOfTwo = (n: number): boolean => n > 0 && (n & (n - 1)) === 0
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { isPowerOfTwo } from "../is_power_of_2"
2+
3+
4+
describe('IsPowerOfTwo' , () => {
5+
it.each([
6+
[0, false],
7+
[1, true],
8+
[4, true],
9+
[1024, true],
10+
[1025, false],
11+
])('Check if %i is a power of 2 or not', (number, expected) => {
12+
expect(isPowerOfTwo(number)).toBe(expected);
13+
});
14+
})

0 commit comments

Comments
 (0)