Skip to content

Commit a7fa307

Browse files
feat: add isPowerOfTwo algorithm
1 parent 5c39e87 commit a7fa307

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

‎Maths/IsPowerOfTwo.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @function isPowerOfTwo
3+
* @description Checks whether a given positive integer is a power of two.
4+
* A number is a power of two if it can be expressed as 2^n where n
5+
* is a non-negative integer. Uses bitwise AND for efficient checking.
6+
* @param {number} n - A positive integer
7+
* @returns {boolean} - True if n is a power of two, false otherwise
8+
* @see https://en.wikipedia.org/wiki/Power_of_two
9+
* @example isPowerOfTwo(1) => true
10+
* @example isPowerOfTwo(16) => true
11+
* @example isPowerOfTwo(18) => false
12+
*/
13+
const isPowerOfTwo = (n) => {
14+
if (!Number.isInteger(n) || n < 1) {
15+
throw new TypeError('Input must be a positive integer')
16+
}
17+
return (n & (n - 1)) === 0
18+
}
19+
20+
export { isPowerOfTwo }

‎Maths/test/IsPowerOfTwo.test.js‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { isPowerOfTwo } from '../IsPowerOfTwo.js'
2+
3+
describe('isPowerOfTwo', () => {
4+
test('1 is a power of two (2^0)', () => {
5+
expect(isPowerOfTwo(1)).toBe(true)
6+
})
7+
8+
test('2 is a power of two (2^1)', () => {
9+
expect(isPowerOfTwo(2)).toBe(true)
10+
})
11+
12+
test('4 is a power of two (2^2)', () => {
13+
expect(isPowerOfTwo(4)).toBe(true)
14+
})
15+
16+
test('16 is a power of two (2^4)', () => {
17+
expect(isPowerOfTwo(16)).toBe(true)
18+
})
19+
20+
test('1024 is a power of two (2^10)', () => {
21+
expect(isPowerOfTwo(1024)).toBe(true)
22+
})
23+
24+
test('3 is NOT a power of two', () => {
25+
expect(isPowerOfTwo(3)).toBe(false)
26+
})
27+
28+
test('18 is NOT a power of two', () => {
29+
expect(isPowerOfTwo(18)).toBe(false)
30+
})
31+
32+
test('100 is NOT a power of two', () => {
33+
expect(isPowerOfTwo(100)).toBe(false)
34+
})
35+
36+
test('throws TypeError for zero', () => {
37+
expect(() => isPowerOfTwo(0)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for negative input', () => {
41+
expect(() => isPowerOfTwo(-4)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for float input', () => {
45+
expect(() => isPowerOfTwo(4.5)).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)