File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
+ } )
You can’t perform that action at this time.
0 commit comments