-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added algo for checking the number is power of four or not
- Loading branch information
madhuredra
committed
Sep 11, 2023
1 parent
00e40e6
commit 0e154ec
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/* | ||
author: @dev-madhurendra | ||
This script will check whether the given | ||
number is a power of four or not. | ||
A number will be power of four if and only if there is a 1 in the binary | ||
of the digit and it will be at the first position | ||
n n-1%3==0 (n-1)bin (n)bin | ||
1 0 0 1 - 4^0 | ||
4 3 011 100 - 4^1 | ||
16 15 01111 10000 - 4^2 | ||
64 63 011111 1000000 - 4^3 | ||
a) There is only one bit set in the binary representation of n (or n is a power of 2) | ||
b) There is only one bit unset in the n-1 | ||
c) And the and of n&n-1 will be 0 | ||
d) N-1 will be divisble by 3 | ||
*/ | ||
|
||
const IsPowerOfFour = (n) => ((n > 0) && ((n & n - 1) === 0) && (n % 3 === 1)) | ||
|
||
export { IsPowerOfFour } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { IsPowerOfFour } from '../IsPowerofFour' | ||
|
||
describe('IsPowerOfFour', () => { | ||
it.each([ | ||
[0, false], | ||
[4, true], | ||
[16, true], | ||
[12, false], | ||
[64, true], | ||
[-64, false] | ||
])('should return the number is power of four or not', (n, expected) => { | ||
expect(IsPowerOfFour(n)).toBe(expected) | ||
}) | ||
}) |