【LeetCode】371. Sum of Two Integers 两整数之和(Easy)(JAVA)
题目地址: https://leetcode.com/problems/sum-of-two-integers/
题目描述:
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
题目大意
不使用运算符 + 和 - ,计算两整数 a 、b 之和。
解题方法
- 先计算出 a 和 b 位不同的地方也就是 a ^ b 进行 a, b 的异或,可以得到不同的地方
- 计算出位相同的地方,a & b, 相同的地方肯定是需要进位的,所有需要 (a & b) << 1 左移以为,也就是进位,如果这里得到为 0 就结束了
- 重复步骤一和步骤二
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int temp = a ^ b;
b = (a & b) << 1;
a = temp;
}
return a;
}
}
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:35.4 MB,击败了44.75% 的Java用户
![](https://img-blog.csdnimg.cn/20201107174624800.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE2OTI3ODUz,size_16,color_FFFFFF,t_70#pic_center)