File tree 4 files changed +697
-82
lines changed
4 files changed +697
-82
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ author: @Aayushi-Mittal
3
+
4
+ This script will check whether the given
5
+ number is a power of two or not.
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
+
23
+ */
24
+
25
+ export const IsPowerOfTwo = ( n ) => {
26
+ if ( n != 0 && ( n & ( n - 1 ) ) == 0 ) return true
27
+ else return false
28
+ }
Original file line number Diff line number Diff line change
1
+ import { IsPowerOfTwo } from '../IsPowerOfTwo'
2
+
3
+ test ( 'Check if 0 is a power of 2 or not:' , ( ) => {
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 )
10
+ expect ( res ) . toBe ( false )
11
+ } )
12
+
13
+ test ( 'Check if 4 is a power of 2 or not:' , ( ) => {
14
+ const res = IsPowerOfTwo ( 4 )
15
+ expect ( res ) . toBe ( true )
16
+ } )
17
+
18
+ test ( 'Check if 1024 is a power of 2 or not:' , ( ) => {
19
+ const res = IsPowerOfTwo ( 1024 )
20
+ expect ( res ) . toBe ( true )
21
+ } )
22
+
23
+ test ( 'Check if 1025 is a power of 2 or not:' , ( ) => {
24
+ const res = IsPowerOfTwo ( 1025 )
25
+ expect ( res ) . toBe ( false )
26
+ } )
Original file line number Diff line number Diff line change 10
10
11
11
## Bit-Manipulation
12
12
* [ BinaryCountSetBits] ( https://github.com/TheAlgorithms/Javascript/blob/master/Bit-Manipulation/BinaryCountSetBits.js )
13
+ * [ IsPowerOfTwo] ( https://github.com/TheAlgorithms/Javascript/blob/master/Bit-Manipulation/IsPowerOfTwo.js )
13
14
* [ SetBit] ( https://github.com/TheAlgorithms/Javascript/blob/master/Bit-Manipulation/SetBit.js )
14
15
15
16
## Cache
You can’t perform that action at this time.
0 commit comments