371. Sum of Two Integers
- Total Accepted: 37210
- Total Submissions: 71785
- Difficulty: Easy
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.
给你两个数,不允许用加减运算符,求sum值
不允许用加法和减法,那么肯定也不能用乘法除法,因为乘法和除法是基于加法减法实现的,所以第一想法就是位运算。
先看异或运算 1 ^ 1 = 0 ,0 ^ 1 = 1,1 ^ 0 = 1, 0 ^ 0 = 0,再来看加法,不考虑进位的情况下,1 + 1 = 0,1 + 0 = 1,0 + 1 = 1,0 + 0 = 0,所以可以把异或运算
看成不考虑进位的加法。那么我们需要考虑的就是怎么处理进位了,显然相同位置都为1时才会进位,这正好符合&运算,又因为进位是进到高位上,
所以为(a & b) << 1,这么一直处理,直到一个数为0。
public class Solution {
public int getSum(int a, int b) {
while(a != 0){
int temp = (a & b) << 1;
b = a ^ b;
a = temp;
}
return b;
}
}