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

ตรวจสอบเลขยกกำลัง 2 (Power of Two) ใน Python

ภาพรวม

โจทย์ตรวจสอบว่าจำนวนเต็มบวก 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 manipulationO(1)แม่นยำ 100%แนะนำมากที่สุด
math.log2O(1)อาจมีปัญหา precisionสำหรับ n ใหญ่มาก

ผลลัพธ์

True