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

โปรแกรม Python บวกเลขสองจำนวน (Bitwise Adder)

โจทย์: บวกเลขใหญ่ 2 จำนวน แสดงผล วิธีตรงไปตรงมา: ใช้ + หรือ sum()

แนวทาง Bitwise Adder: ใช้หลักการ Full Adder คำนวณ Sum และ Carry ด้วย Bitwise operators

  • Carry = x & y (bitwise AND)
  • Sum = x ^ y (bitwise XOR)
  • Shift carry << 1
  • ทำซ้ำจน carry = 0

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

def Add(x, y):
    while y != 0:
        carry = x & y
        x = x ^ y
        y = carry << 1
    return x

print(Add(19, 34))

ผลลัพธ์

53

โปรแกรม Python บวกเลขสองจำนวน (Bitwise Adder)

สรุป

เรียนรู้วิธีบวกเลข 2 จำนวนด้วย Bitwise Operators (Full Adder logic) แทนการใช้ + แบบตรงไปตรงมา