How to round a number to the next power of 2 in TypeScript

1 Answer

0 votes
/**
 * Rounds an integer up to the next power of 2.
 *
 * returns the next power of 2 greater than or equal to n
 */
function roundToNextPowerOf2(n: number): number {
  if (n <= 0) return 1;

  return 2 ** Math.ceil(Math.log2(n));
}

const num = 21;
console.log(`Next power of 2: ${roundToNextPowerOf2(num)}`);



/*
run:
 
"Next power of 2: 32"

*/

 



answered 14 hours ago by avibootz

Related questions

...