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.

题目出处:https://leetcode.com/problems/sum-of-two-integers/


题意:不用+或者-实现加法。


思路:先用a^b得两位相加的结果,再用a&b得到进位,最后加上进位。


代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int (int a, int b) {
while(b)
{
int carry=a&b;
a=a^b;
b=carry<<1;
}
return a;
}
};