Skip to content

Commit d636454

Browse files
committed
Check if number is already power of two
1 parent 372348f commit d636454

File tree

2 files changed

+6
-3
lines changed

2 files changed

+6
-3
lines changed

Bit-Manipulation/NextPowerOfTwo.js

+3
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@
22
*
33
* This script will find next power of two
44
* of given number.
5+
* More about it:
6+
* https://www.techiedelight.com/round-next-highest-power-2/
57
*
68
*/
79

810
export const nextPowerOfTwo = (n) => {
11+
if (n > 0 && (n & (n - 1)) === 0) return n
912
let result = 1
1013
while (n > 0) {
1114
result = result << 1

Bit-Manipulation/test/NextPowerOfTwo.test.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ describe('NextPowerOfTwo', () => {
44
it.each`
55
input | result
66
${0} | ${1}
7-
${1} | ${2}
8-
${2} | ${4}
7+
${1} | ${1}
8+
${2} | ${2}
99
${3} | ${4}
1010
${5} | ${8}
1111
${125} | ${128}
12-
${1024} | ${2048}
12+
${1024} | ${1024}
1313
${10000} | ${16384}
1414
`('returns $result when is given $input', ({ input, result }) => {
1515
const res = nextPowerOfTwo(input)

0 commit comments

Comments
 (0)