目录
使用加法运算符
int a = 1, b = 2;
int c = a + b;
cout << c << endl;
使用位运算
int a = 1, b = 2;
int c = a ^ b;
int d = (a & b) << 1;
while (d != 0) {
int tmp = c;
c = c ^ d;
d = (tmp & d) << 1;
}
cout << c << endl;
使用递归
int add(int a, int b) {
if (b == 0) {
return a;
} else {
return add(a ^ b, (a & b) << 1);
}
}
int a = 1, b = 2;
int c = add(a, b);
cout << c << endl;
使用STL库
#include <numeric>
int a = 1, b = 2;
int c = std::accumulate(&a, &b + 1, 0);
cout << c << endl;