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)兩個(gè)整數(shù)的加法件舵,不允許使用+-號(hào)唤反。
思路
利用bit操作韵洋,sum保存不算進(jìn)位情況下的和茉唉,carry保存進(jìn)位(兩個(gè)對(duì)應(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)位的情況下計(jì)算和
carry=(a&b)<<1; //進(jìn)位
return getSum(sum,carry);
}
};