ภาพรวม
โจทย์ตรวจสอบว่าจำนวนเต็มบวก n เป็นกำลังของ 2 หรือไม่ (1, 2, 4, 8, 16, 32, ...)
ตัวอย่าง
อินพุต: 1024 → True (2¹⁰)
โค้ด Python (วิธีหาร 2 ซ้ำ)
class Solution:
def solve(self, n):
while n > 1:
n /= 2
return n == 1
ob = Solution()
print(ob.solve(1024))
วิธีที่ดีกว่า: Bit Manipulation
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
อธิบาย: กำลังของ 2 ใน binary มีแค่ 1 bit เดียว (1000...), n-1 จะเป็น 0111... → AND = 0
วิธีอื่น: math.log2
import math
def is_power_of_two(n):
return n > 0 and math.log2(n).is_integer()
เปรียบเทียบ
| วิธี | เวลา | ความแม่นยำ | หมายเหตุ |
|---|---|---|---|
| หาร 2 ซ้ำ | O(log n) | ปัญหา float precision | เข้าใจง่าย |
| Bit manipulation | O(1) | แม่นยำ 100% | แนะนำมากที่สุด |
| math.log2 | O(1) | อาจมีปัญหา precision | สำหรับ n ใหญ่มาก |
ผลลัพธ์
True