写一个方法,找出最接近当前的数的2的指数的数

39 阅读1分钟

"```javascript function findClosestPowerOfTwo(num) { let power = Math.floor(Math.log2(num)); let lowerPower = Math.pow(2, power); let higherPower = Math.pow(2, power + 1);

if (Math.abs(num - lowerPower) < Math.abs(num - higherPower)) {
    return lowerPower;
} else {
    return higherPower;
}

}

// Example usage console.log(findClosestPowerOfTwo(10)); // Output: 8 console.log(findClosestPowerOfTwo(20)); // Output: 16 console.log(findClosestPowerOfTwo(5)); // Output: 4

"