บวกเลข 2 จำนวนโดยใช้ Bitwise Operators เท่านั้น (ไม่ใช้ +)
อัลกอริธึม
carry = a & b − หาบิตที่ทั้งคู่เป็น 1 (ต้อง Carry)
a = a ^ b − บวกโดยไม่ Count Carry (XOR)
b = carry << 1 − เลื่อน Carry ไปบิตถัดไป
- ทำซ้ำจน
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)
| Loop | num1 (bin) | num2 (bin) | carry (bin) | num1^num2 | carry<<1 |
| Start | 1011 (11) | 0101 (5) | 0001 | 1110 (14) | 0010 (2) |
| 1 | 1110 (14) | 0010 (2) | 0010 | 1100 (12) | 0100 (4) |
| 2 | 1100 (12) | 0100 (4) | 0100 | 1000 (8) | 1000 (8) |
| 3 | 1000 (8) | 1000 (8) | 1000 | 0000 (0) | 10000 (16) |
| 4 | 0000 (0) | 10000 (16) | 0000 | 10000 (16) | 0 |
| End | 10000 (16) | 0 | - | - | - |
Bitwise Operators ใบปิด
| Op | Name | ตัวอย่าง |
| & | Bitwise AND | 1 & 1 = 1 |
| | | Bitwise OR | 1 | 0 = 1 |
| ^ | Bitwise XOR | 1 ^ 1 = 0 |
| ~ | Bitwise NOT | ~1 = 0 |
| << | Left Shift | 1 << 2 = 4 |
| >> | Right Shift | 4 >> 1 = 2 |