在本文中,我们将看到如何在不使用算术运算符(例如+,++,-或-)的情况下将两个数字相加。
为了解决这个问题,我们可以使用二进制加法器逻辑来解决它们。在这种情况下,我们被设计为半加法器和全加法器。这些加法器可以加一位二进制数。通过级联多个加法器,我们可以创建电路以添加更大的数字。
在该加法器中,我们在数字之间执行了XOR运算,然后对于进位执行了ANDing逻辑。此处实现了这些功能以添加两个数字。
#include <iostream>
using namespace std;
int add(int a, int b) {
while (b != 0) { //until there is no carry, iterater
int carry = a & b; //find carry by anding a and b
a = a ^ b; //perform XOR on a and b, and store into a
b = carry << 1; //the carry is shifted one bit to the left, and store it to b
}
return a;
}
int main() {
int a, b;
cout << "Enter two numbers to add: ";
cin >> a >> b;
cout << "The result is: " << add(a, b);
return 0;
}输出结果
Enter two numbers to add: 56 23 The result is: 79