หาเลขที่เป็นกำลังของ 2 (2ⁿ) ที่ใกล้ที่สุดกับตัวเลขที่กำหนด
ตัวอย่าง
365 → 256 (2⁸) ใกล้กว่า 512 (2⁹) |365-256| = 109 < |512-365| = 147
ตัวอย่างโค้ด
const nearestPowerOfTwo = num => {
if (num < 0) num = -num;
let base = 1;
while (base < num) {
if (num - base < base / 2) return base;
base *= 2;
}
return base;
};
console.log(nearestPowerOfTwo(365));
ผลลัพธ์
256
วิธีแบบ Bitwise (เร็วที่สุด)
const nearestPowerOfTwo = num => {
if (num <= 1) return 1;
num = Math.abs(num);
const log2 = Math.log2(num);
const lower = 1 << Math.floor(log2);
const upper = 1 << Math.ceil(log2);
return (num - lower < upper - num) ? lower : upper;
};
ใช้ Math.log2 และ Bit Shift 1 << n คำนวณ 2ⁿ ได้เร็ว