如何在不使用 ++ 运算符、+运算符或 C/C++ 中的任何其他算术运算符的情况下为两个数字求和?
在本文中,我们将看到在不使用 +, ++, -, 或 -- 等算术运算符的情况下,如何为两个数字求和。
为了解决这个问题,我们可以使用二进制加法器逻辑来解决它们。在这种情况下,我们设计了半加法器和全加法器。这些加法器可以为一位二进制数求和。通过级联多个加法器,我们可以创建电路来计算更大的数字。
在该加法器中,我们在数字之间执行 XOR 操作,然后为进位执行 AND 操作。此处的这些特性用于计算两个数字的和。
示例代码
#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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP