Problem: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.
题目:计算a和b的和,不使用加减运算符。
思路:使用异或,与等逻辑运算。(参考计算机组成原理中补码加减法等)
使用异或保留二进制中的不同位,与运算保留相同位,左移则实现进位操作,再用异或运算实现相加,同时与运算左移实现进位,直至与运算后为0停止。
代码:
class Solution {
public int getSum(int a, int b) {
return (b==0)?a:getSum(a^b,(a&b)<<1);
//return ((a&b)<<1)|(a^b);
}
}