From d6364548aa2a1e3e4d58a27dbfb6752eec8d9029 Mon Sep 17 00:00:00 2001 From: Indre Maksimovaite Date: Mon, 11 Oct 2021 20:24:38 +0300 Subject: [PATCH] Check if number is already power of two --- Bit-Manipulation/NextPowerOfTwo.js | 3 +++ Bit-Manipulation/test/NextPowerOfTwo.test.js | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Bit-Manipulation/NextPowerOfTwo.js b/Bit-Manipulation/NextPowerOfTwo.js index b5999252f..623469e4d 100644 --- a/Bit-Manipulation/NextPowerOfTwo.js +++ b/Bit-Manipulation/NextPowerOfTwo.js @@ -2,10 +2,13 @@ * * 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 diff --git a/Bit-Manipulation/test/NextPowerOfTwo.test.js b/Bit-Manipulation/test/NextPowerOfTwo.test.js index 271b08249..073224046 100644 --- a/Bit-Manipulation/test/NextPowerOfTwo.test.js +++ b/Bit-Manipulation/test/NextPowerOfTwo.test.js @@ -4,12 +4,12 @@ describe('NextPowerOfTwo', () => { it.each` input | result ${0} | ${1} - ${1} | ${2} - ${2} | ${4} + ${1} | ${1} + ${2} | ${2} ${3} | ${4} ${5} | ${8} ${125} | ${128} - ${1024} | ${2048} + ${1024} | ${1024} ${10000} | ${16384} `('returns $result when is given $input', ({ input, result }) => { const res = nextPowerOfTwo(input)