http://blog.youkuaiyun.com/shijing_0214/article/details/10996951
题目地址:https://leetcode.com/problems/sum-of-two-integers/#/description
简单理解:
题目需要我们实现两个整数的加法,但是不能使用"+"和"-"操作符
我的解法:
使用逻辑运算符来实现:
1. bit的加法使用^运算符,如1^1=0,1^0=1,0^0=0;
2. 进位的运算,使用&操作符和<<逻辑左移操作.如1+1=10的运算过程为:1&1=1,1<<1= 10;
代码如下:
class Solution {
public:
int getSum(int a,int b){
while(b){
int temp = a^b;
int carry = (a&b)<<1;
a = temp;
b = carry;
}
return a;
}
};