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.
實(shí)現(xiàn)兩個整數(shù)的加法,不允許使用+-號。
思路
利用bit操作,sum保存不算進(jìn)位情況下的和,carry保存進(jìn)位(兩個對應(yīng)bit都是1才有進(jìn)位,所以利用&再左移一位即可)
class Solution {
public:
int getSum(int a, int b) {
if(b==0) return a; //不含進(jìn)位的情況
int sum=0,carry=0;
sum=a^b; //不算進(jìn)位的情況下計算和
carry=(a&b)<<1; //進(jìn)位
return getSum(sum,carry);
}
};