Skip to content

Instantly share code, notes, and snippets.

@ENAML
Last active June 6, 2018 06:42
Show Gist options
  • Save ENAML/f149d1db99d14061f7eb2e2f552fdc65 to your computer and use it in GitHub Desktop.
Save ENAML/f149d1db99d14061f7eb2e2f552fdc65 to your computer and use it in GitHub Desktop.
/*
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