剑指 Offer 65 不用加减乘除做加法
概述
https://leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof/
位运算实现加法
https://www.jianshu.com/p/7bba031b11e7
由于 C++ 中禁止对负数左移(runtime error: left shift of negative value),所以我们在左移前需要进行类型转换。
class Solution {
public:
int add(int a, int b) {
int sum = a ^ b;
int carry = (unsigned int) (a & b) << 1;
if (carry == 0) return sum;
else return add(sum, carry);
}
};
Links: sword-offer-65