mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 08:16:50 +08:00
chore: Merge pull request #777 from indremak/add-next-power-of-two-algorithm
Add next power of two algorithm
This commit is contained in:
18
Bit-Manipulation/NextPowerOfTwo.js
Normal file
18
Bit-Manipulation/NextPowerOfTwo.js
Normal file
@ -0,0 +1,18 @@
|
||||
/**
|
||||
*
|
||||
* This script will find next power of two
|
||||
* of given number.
|
||||
* More about it:
|
||||
* https://www.techiedelight.com/round-next-highest-power-2/
|
||||
*
|
||||
*/
|
||||
|
||||
export const nextPowerOfTwo = (n) => {
|
||||
if (n > 0 && (n & (n - 1)) === 0) return n
|
||||
let result = 1
|
||||
while (n > 0) {
|
||||
result = result << 1
|
||||
n = n >> 1
|
||||
}
|
||||
return result
|
||||
}
|
18
Bit-Manipulation/test/NextPowerOfTwo.test.js
Normal file
18
Bit-Manipulation/test/NextPowerOfTwo.test.js
Normal file
@ -0,0 +1,18 @@
|
||||
import { nextPowerOfTwo } from '../NextPowerOfTwo'
|
||||
|
||||
describe('NextPowerOfTwo', () => {
|
||||
it.each`
|
||||
input | result
|
||||
${0} | ${1}
|
||||
${1} | ${1}
|
||||
${2} | ${2}
|
||||
${3} | ${4}
|
||||
${5} | ${8}
|
||||
${125} | ${128}
|
||||
${1024} | ${1024}
|
||||
${10000} | ${16384}
|
||||
`('returns $result when is given $input', ({ input, result }) => {
|
||||
const res = nextPowerOfTwo(input)
|
||||
expect(res).toBe(result)
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user