Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7ce688b

Browse files
Updated the code and did the required changes
1 parent e978f43 commit 7ce688b

File tree

2 files changed

+24
-8
lines changed

2 files changed

+24
-8
lines changed

‎Bit-Manipulation/IsPowerOfTwo.js

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,25 @@
44
This script will check whether the given
55
number is a power of two or not.
66
7+
A number will be a power of two if only one bit is set and rest are unset.
8+
This is true for all the cases except 01 because (2^0 = 1) which is not a power of 2.
9+
For eg: 10 (2^1 = 2), 100 (2^2 = 4), 10000 (2^4 = 16)
10+
11+
Reference Link: https://www.hackerearth.com/practice/notes/round-a-number-to-the-next-power-of-2/
12+
13+
If we will subtract 1 from a number that is a power of 2 we will get it's 1's complement.
14+
And we know that 1's complement is just opp. of that number.
15+
So, (n & (n-1)) will be 0.
16+
17+
For eg: (1000 & (1000-1))
18+
1 0 0 0 // Original Number (8)
19+
0 1 1 1 // After Subtracting 1 (8-1 = 7)
20+
_______
21+
0 0 0 0 // will become 0
22+
723
*/
824

925
export const IsPowerOfTwo = (n) => {
10-
if ((n&(n-1))==0 && n!=0)
11-
return true;
12-
else
13-
return false;
26+
if (n != 0 && (n & (n - 1)) == 0) return true
27+
else return false
1428
}
15-
16-
// console.log(IsPowerOfTwo(0));
17-

‎Bit-Manipulation/test/IsPowerOfTwo.test.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import {IsPowerOfTwo} from '../IsPowerOfTwo'
22

33
test('Check if 0 is a power of 2 or not:', () => {
4-
const res = IsPowerOfTwo(1, 0)
4+
const res = IsPowerOfTwo(0)
5+
expect(res).toBe(false)
6+
})
7+
8+
test('Check if 0 is a power of 2 or not:', () => {
9+
const res = IsPowerOfTwo(1)
510
expect(res).toBe(false)
611
})
712

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /