ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อทำความเข้าใจวิธีรวมจำนวนเต็มสองตัวโดยไม่ต้องใช้ตัวดำเนินการเลขคณิตใน C/C++
สำหรับการเพิ่มจำนวนเต็มสองจำนวนโดยไม่ใช้ตัวดำเนินการเลขคณิต เราสามารถทำได้โดยใช้พอยน์เตอร์หรือตัวดำเนินการระดับบิต
ตัวอย่าง
การใช้พอยน์เตอร์
#include <iostream>
using namespace std;
int sum(int a, int b){
int *p = &a;
return (int)&p[b];
}
int main() {
int add = sum(2,3);
cout << add << endl;
return 0;
} ผลลัพธ์
5
ตัวอย่าง
การใช้ตัวดำเนินการระดับบิต
#include <iostream>
using namespace std;
int sum(int a, int b){
int s = a ^ b;
int carry = a & b;
if (carry == 0)
return s;
else
return sum(s, carry << 1);
}
int main() {
int add = sum(2,3);
cout << add << endl;
return 0;
} ผลลัพธ์
5