Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การตรวจสอบว่าเป็น Power of 4 หรือไม่ใน JavaScript

ปัญหา

ตรวจสอบว่าตัวเลขเป็น power of 4 (4^k) หรือไม่

ตัวอย่าง

2356 -> false, 16 -> true

ตัวอย่างโค้ด

const num1 = 2356;
const num2 = 16;

const isPowerOfFour = (num = 1) => {
  let bool = false;
  for (let i = 0; i < 16; i++) {
    if (Math.pow(4, i) === num) {
      bool = true;
      return bool;
    }
  }
  return bool;
};

console.log(isPowerOfFour(num1));
console.log(isPowerOfFour(num2));

ผลลัพธ์

false true

คำอธิบายและวิธีที่ดีกว่า

โค้ดต้นฉบับวนลูป 0-15 (4^15 ~ 1e9) ไม่ครอบคลุม int32 ทั้งหมด

วิธี Bit manipulation (O(1)):

const isPowerOfFour = (num) => {
  return num > 0 && (num & (num - 1)) === 0 && (num & 0x55555555) !== 0;
};
// num > 0, เป็น power of 2 (only 1 bit set), และ bit อยู่ตำแหน่งคู่ (0x55555555 = 0101... pattern)

หรือใช้ Math: Number.isInteger(Math.log(num) / Math.log(4))