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

ตรวจสอบว่าเลขมี Bit ตั้งค่า (Set) เฉพาะ First และ Last Bit ด้วย Python

โจทย์: กำหนดเลข n ตรวจสอบว่า Binary Representation มี Bit 1 เฉพาะตำแหน่งแรก (LSB) และตำแหน่งสุดท้าย (MSB) เท่านั้น

ตัวอย่าง

n = 17 (10001) → True (Bit 0 และ Bit 4 เป็น 1, อื่นๆ เป็น 0)

อัลกอริทึม

  1. ถ้า n == 1 → True (Binary: 1)
  2. n - 1 ต้องเป็น Power of 2 (เช่น 17-1=16=2^4)
  3. ตรวจสอบ Power of 2: (n & (n-1)) == 0

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

def is_pow_of_two(n):
    return (n & (n-1)) == 0

def solve(n):
    if n == 1:
        return True
    return is_pow_of_two(n-1)

n = 17
print(solve(n))

Input / Output

Input: 17
Output: True