ในปัญหานี้ เราได้รับจำนวนเต็ม N งานของเราคือการตรวจสอบว่า N เป็นกำลังของ 4 หรือไม่
ตัวอย่างเพื่อเข้าใจปัญหา
Input: N = 64 Output: Yes
เพราะ 43 = 64
วิธีการแก้ปัญหา
วิธีง่ายคือหาร N ด้วย 4 ซ้ำๆ ถ้าหารลงตัวจนเหลือ 1 แสดงว่าเป็นกำลังของ 4
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
bool isPowerOf4(int n) {
if (n == 0) return 0;
while (n != 1) {
if (n % 4 != 0) return 0;
n = n / 4;
}
return 1;
}
int main() {
int n = 123454;
if (isPowerOf4(n)) cout << "The number is a power of 4";
else cout << "The number is not a power of 4";
return 0;
}
ผลลัพธ์
The number is not a power of 4
วิธีเพิ่มเติม: ใช้ bitwise operation - ตัวเลขที่เป็นกำลังของ 4 จะมีบิตที่ 1 อยู่ที่ตำแหน่งคู่ (0, 2, 4, ...) และมีเพียงบิตเดียวที่เป็น 1