Skip to content

Commit f14c930

Browse files
dev-madhurendramadhuredra
andauthored
feat: added is power of 4 method (TheAlgorithms#158)
Co-authored-by: madhuredra <[email protected]>
1 parent a710e64 commit f14c930

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

bit_manipulation/is_power_of_4.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* @author : dev-madhurendra<https://github.com/dev-madhurendra>
3+
* Checks whether the given number is a power of four or not.
4+
*
5+
* A number is considered a power of four if and only if there is a single '1' bit in its binary representation,
6+
* and that '1' bit is at the first position, followed by an even number of '0' bits.
7+
*
8+
* @param {number} n - The input number to check.
9+
* @returns {boolean} True if the number is a power of four, false otherwise.
10+
*
11+
* @example
12+
* const result = isPowerOfFour(16); // Returns true (16 is 4^2)
13+
* const result2 = isPowerOfFour(5); // Returns false (5 is not a power of four)
14+
*/
15+
export const isPowerOfFour = (n: number): boolean => ((n > 0) && ((n & n - 1) === 0) && (n % 3 === 1))
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { isPowerOfFour } from "../is_power_of_4"
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 %i is power of four or not', (n, expected) => {
12+
expect(isPowerOfFour(n)).toBe(expected)
13+
})
14+
})

0 commit comments

Comments
 (0)