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 145.
Then the output should be 128 because 145 is the nearest such number to 128 which can be represented as 2^n for some whole number value of n.
Example
The code for this will be −
const num = 145;
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 −
128