Nearest power 2 of a number - JavaScript


We are required to write a JavaScript function that takes in a number and returns a number that can be represented as a power of 2 which is nearest to the input number.

For example −

If the input number if 365, then the output should be 256, because 256 is the nearest such number to 365 which can be represented as 2^n for some whole number value of n.

Example

Let’s write the code for this function −

const num = 365;
const nearestPowerOfTwo = num => {
   // dealing only with non-negative numbers
   if(num < 0){
      num *= -1;
   }
   let base = 1;
   while(base < num){
      if(num - base < Math.floor(base / 2)){
         return base;
      };
      base *= 2;
   };
   return base;
};
console.log(nearestPowerOfTwo(num));

Output

The output in the console: −

256

Updated on: 15-Sep-2020

682 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements