mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-11 15:11:33 +08:00
add algorithm that calculates next power of two
This commit is contained in:
15
Bit-Manipulation/NextPowerOfTwo.js
Normal file
15
Bit-Manipulation/NextPowerOfTwo.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
/**
|
||||||
|
*
|
||||||
|
* This script will find next power of two
|
||||||
|
* of given number.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const nextPowerOfTwo = (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} | ${2}
|
||||||
|
${2} | ${4}
|
||||||
|
${3} | ${4}
|
||||||
|
${5} | ${8}
|
||||||
|
${125} | ${128}
|
||||||
|
${1024} | ${2048}
|
||||||
|
${10000} | ${16384}
|
||||||
|
`('returns $result when is given $input', ({ input, result }) => {
|
||||||
|
const res = nextPowerOfTwo(input)
|
||||||
|
expect(res).toBe(result)
|
||||||
|
})
|
||||||
|
})
|
@ -41,7 +41,6 @@ const kelvinToCelsius = (kelvin) => {
|
|||||||
// Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
|
// Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
|
||||||
// Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
|
// Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
|
||||||
return Math.round((kelvin) - 273.15)
|
return Math.round((kelvin) - 273.15)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const kelvinToFahrenheit = (kelvin) => {
|
const kelvinToFahrenheit = (kelvin) => {
|
||||||
|
Reference in New Issue
Block a user