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

ตรวจสอบว่าการแทนค่าบิตเตอรี่ของสองจำนวนเป็น Anagram กันหรือไม่ ใน Python


ปัญหา

ให้จำนวน x และ y ตรวจสอบว่ารูปแบบไบนารีของทั้งสองเป็น anagram กันหรือไม่ (มีจำนวน 1 เท่ากัน)

ตัวอย่าง

x = 9 (1001₂), y = 12 (1100₂) → ทั้งคู่มี 1 สองบิต → True

ข้อสังเกต

Binary anagram ⟺ จำนวน set bits เท่ากัน (เพราะมีแค่ 0 และ 1)

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

def count_set_bits(n):
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count

def solve(x, y):
    return count_set_bits(x) == count_set_bits(y)

# หรือใช้ built-in
def solve_builtin(x, y):
    return bin(x).count('1') == bin(y).count('1')

print(solve(9, 12))  # True

อินพุต / เอาต์พุต

Input:  9, 12
Output: True