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

2 Answers

0 votes
/**
 * Rounds a positive integer to the nearest power of 2.
 * returns the nearest power of 2
 */
function roundToNearestPowerOf2(n: number): number {
  if (n <= 0) return 0;

  let prevPower: number = 1;
  while (prevPower * 2 <= n) {
    prevPower *= 2;
  }

  const nextPower: number = prevPower * 2;
  return n - prevPower < nextPower - n ? prevPower : nextPower;
}

const num = 37;

console.log(`Nearest power of 2: ${roundToNearestPowerOf2(num)}`);




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

*/

 



answered Oct 31, 2025 by avibootz
edited Oct 31, 2025 by avibootz
0 votes
function roundToNearestPowerOf2(n: number): number {
  if (n <= 0) return 0;

  // Compute the previous power of 2 using bit length
  const prevPower = 1 << (Math.floor(Math.log2(n)));

  // Compute the next power of 2
  const nextPower = prevPower << 1;

  // Return the one closest to n
  return n - prevPower < nextPower - n ? prevPower : nextPower;
}

const num = 37;

console.log(`Nearest power of 2: ${roundToNearestPowerOf2(num)}`);




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

*/

 



answered Oct 31, 2025 by avibootz
...