mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
Check if number is already power of two
This commit is contained in:
@ -2,10 +2,13 @@
|
|||||||
*
|
*
|
||||||
* This script will find next power of two
|
* This script will find next power of two
|
||||||
* of given number.
|
* of given number.
|
||||||
|
* More about it:
|
||||||
|
* https://www.techiedelight.com/round-next-highest-power-2/
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export const nextPowerOfTwo = (n) => {
|
export const nextPowerOfTwo = (n) => {
|
||||||
|
if (n > 0 && (n & (n - 1)) === 0) return n
|
||||||
let result = 1
|
let result = 1
|
||||||
while (n > 0) {
|
while (n > 0) {
|
||||||
result = result << 1
|
result = result << 1
|
||||||
|
@ -4,12 +4,12 @@ describe('NextPowerOfTwo', () => {
|
|||||||
it.each`
|
it.each`
|
||||||
input | result
|
input | result
|
||||||
${0} | ${1}
|
${0} | ${1}
|
||||||
${1} | ${2}
|
${1} | ${1}
|
||||||
${2} | ${4}
|
${2} | ${2}
|
||||||
${3} | ${4}
|
${3} | ${4}
|
||||||
${5} | ${8}
|
${5} | ${8}
|
||||||
${125} | ${128}
|
${125} | ${128}
|
||||||
${1024} | ${2048}
|
${1024} | ${1024}
|
||||||
${10000} | ${16384}
|
${10000} | ${16384}
|
||||||
`('returns $result when is given $input', ({ input, result }) => {
|
`('returns $result when is given $input', ({ input, result }) => {
|
||||||
const res = nextPowerOfTwo(input)
|
const res = nextPowerOfTwo(input)
|
||||||
|
Reference in New Issue
Block a user