Skip to content

Commit 6379d1b

Browse files
authored
chore: Merge pull request #777 from indremak/add-next-power-of-two-algorithm
Add next power of two algorithm
2 parents 4a06588 + d636454 commit 6379d1b

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

Bit-Manipulation/NextPowerOfTwo.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
*
3+
* This script will find next power of two
4+
* of given number.
5+
* More about it:
6+
* https://www.techiedelight.com/round-next-highest-power-2/
7+
*
8+
*/
9+
10+
export const nextPowerOfTwo = (n) => {
11+
if (n > 0 && (n & (n - 1)) === 0) return n
12+
let result = 1
13+
while (n > 0) {
14+
result = result << 1
15+
n = n >> 1
16+
}
17+
return result
18+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { nextPowerOfTwo } from '../NextPowerOfTwo'
2+
3+
describe('NextPowerOfTwo', () => {
4+
it.each`
5+
input | result
6+
${0} | ${1}
7+
${1} | ${1}
8+
${2} | ${2}
9+
${3} | ${4}
10+
${5} | ${8}
11+
${125} | ${128}
12+
${1024} | ${1024}
13+
${10000} | ${16384}
14+
`('returns $result when is given $input', ({ input, result }) => {
15+
const res = nextPowerOfTwo(input)
16+
expect(res).toBe(result)
17+
})
18+
})

0 commit comments

Comments
 (0)