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

โปรแกรม C++ บวกเลขด้วย Bitwise Operators

บวกเลข 2 จำนวนโดยใช้ Bitwise Operators เท่านั้น (ไม่ใช้ +)

อัลกอริธึม

  1. carry = a & b − หาบิตที่ทั้งคู่เป็น 1 (ต้อง Carry)
  2. a = a ^ b − บวกโดยไม่ Count Carry (XOR)
  3. b = carry << 1 − เลื่อน Carry ไปบิตถัดไป
  4. ทำซ้ำจน b == 0 (ไม่มี Carry เหลือ)

โค้ดโปรแกรม

#include <iostream>
using namespace std;

int main() {
    int num1, num2, carry;
    cout << "Enter first number: ";  cin >> num1;
    cout << "Enter second number: "; cin >> num2;
    
    while (num2 != 0) {
        carry = num1 & num2;      // AND: หา Carry bits
        num1 = num1 ^ num2;       // XOR: บวกไม่รวม Carry
        num2 = carry << 1;        // Shift Carry 左 1 bit
    }
    
    cout << "The Sum is: " << num1;
    return 0;
}

ผลลัพธ์

Enter first number: 11
Enter second number: 5
The Sum is: 16

Trace ตัวอย่าง (11 + 5)

Loopnum1 (bin)num2 (bin)carry (bin)num1^num2carry<<1
Start1011 (11)0101 (5)00011110 (14)0010 (2)
11110 (14)0010 (2)00101100 (12)0100 (4)
21100 (12)0100 (4)01001000 (8)1000 (8)
31000 (8)1000 (8)10000000 (0)10000 (16)
40000 (0)10000 (16)000010000 (16)0
End10000 (16)0---

Bitwise Operators ใบปิด

OpNameตัวอย่าง
&Bitwise AND1 & 1 = 1
|Bitwise OR1 | 0 = 1
^Bitwise XOR1 ^ 1 = 0
~Bitwise NOT~1 = 0
<<Left Shift1 << 2 = 4
>>Right Shift4 >> 1 = 2