File tree 2 files changed +24
-8
lines changed 2 files changed +24
-8
lines changed Original file line number Diff line number Diff line change 4
4
This script will check whether the given
5
5
number is a power of two or not.
6
6
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
+
7
23
*/
8
24
9
25
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
14
28
}
15
-
16
- // console.log(IsPowerOfTwo(0));
17
-
Original file line number Diff line number Diff line change 1
1
import { IsPowerOfTwo } from '../IsPowerOfTwo'
2
2
3
3
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 )
5
10
expect ( res ) . toBe ( false )
6
11
} )
7
12
You can’t perform that action at this time.
0 commit comments