Last active
June 6, 2018 06:42
-
-
Save ENAML/f149d1db99d14061f7eb2e2f552fdc65 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Computes the next power-of-two integer greater than or equal to `num` via binary searching the bits | |
*/ | |
const nextPOT = (num) => { | |
num = num | 0; | |
if (num === 0) { | |
return 0; | |
} | |
let min = 0; | |
let max = 64; // assume numbers in JS are no larger than 64 bits | |
let mid = 0; | |
while (true) { | |
mid = (((min + max) / 2) + min ) | 0; | |
if ( num >> mid > 1 ) { | |
min = mid + 1; | |
} | |
else if (num >> mid < 1) { | |
max = mid; | |
} | |
else { | |
break; | |
} | |
} | |
let res = 1 << mid; | |
return res << (res === num ? 0 : 1); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment