【leetcode】371. Sum of Two Integers

题目

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3.

问题陈述:

求两个整数和,不能用加法

题目思路:

想到了转化成2进制再求和

  1. 异或(^)操作:
    1^0 = 0^1 = 1,0^0 = 1^1 = 0,先求出不考虑进位情况下的各位数字相加的运算结果d
  2. 和(&)操作:
    1^1 = 1,1^0 = 0^1 = 0^0 = 0,然后求出两个数字对应位置都是1的位,也就是需要进位的位置c。
  3. 左移操作(<<):c<<1,前两步操由于没有进位而漏加的部分
  4. 对c和d重复进行上述操作,直到c为0,即没有由于需要进位而漏加的部分。

代码:

class Solution {
public:
int getSum(int a, int b) {
int c = a & b;//进位位置
int result = a^b;
while (c)
{
c = c << 1;
int t = c;
c = result & c;
result = result ^ t;
}
return result;
}
};

结果