File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ author: @dev-madhurendra
3
+
4
+ This script will check whether the given
5
+ number is a power of four or not.
6
+
7
+ A number will be power of four if and only if there is a 1 in the binary
8
+ of the digit and it will be at the first position
9
+
10
+ n n-1%3==0 (n-1)bin (n)bin
11
+ 1 0 0 1 - 4^0
12
+ 4 3 011 100 - 4^1
13
+ 16 15 01111 10000 - 4^2
14
+ 64 63 011111 1000000 - 4^3
15
+
16
+ a) There is only one bit set in the binary representation of n (or n is a power of 2)
17
+ b) There is only one bit unset in the n-1
18
+ c) And the and of n&n-1 will be 0
19
+ d) N-1 will be divisble by 3
20
+ */
21
+
22
+ const IsPowerOfFour = ( n ) => ( ( n > 0 ) && ( ( n & n - 1 ) === 0 ) && ( n % 3 === 1 ) )
23
+
24
+ export { IsPowerOfFour }
Original file line number Diff line number Diff line change
1
+ import { IsPowerOfFour } from '../IsPowerofFour'
2
+
3
+ describe ( 'IsPowerOfFour' , ( ) => {
4
+ it . each ( [
5
+ [ 0 , false ] ,
6
+ [ 4 , true ] ,
7
+ [ 16 , true ] ,
8
+ [ 12 , false ] ,
9
+ [ 64 , true ] ,
10
+ [ - 64 , false ]
11
+ ] ) ( 'should return the number is power of four or not' , ( n , expected ) => {
12
+ expect ( IsPowerOfFour ( n ) ) . toBe ( expected )
13
+ } )
14
+ } )
You can’t perform that action at this time.
0 commit comments