ID | Title | Difficulty | |
---|---|---|---|
Loading... |
371. Sum of Two Integers
Medium
LeetCode
Math, Bit Manipulation
Problem
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
Code
- a + b 相当于 a ^ b 如果不考虑进位的计算
- 使用 int carry = a & b, 可以计算出当前 a 和 b 的进位
class Solution {
public int getSum(int a, int b) {
if(a == 0) return b;
if(b == 0) return a;
while(b != 0){
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
}
按 <- 键看上一题!
370. Range Addition
按 -> 键看下一题!
372. Super Pow