您的位置:首页 > 其它

371. Sum of Two Integers

2016-11-04 17:58 176 查看
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.

思路:看來就用bit運算式
(a&b) << 1 可以表示進位
a^b 就是不進位的狀態
就一直loop 去計算 

class Solution {
public:
int getSum(int a, int b) {

int add = 0;
int inc = 0;

do {
add = a^b;
inc = (a&b) << 1;

a = add;
b = inc;

} while(inc != 0);

return add;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leecode Easy