Sum of Two Integers
Given two integers a and b, return the sum of the two integers without using the + and - operators.
Example 1:
Input: a = 1, b = 1
Output: 2
Example 2:
Input: a = 4, b = 7
Output: 11
Constraints:
-1000 <= a, b <= 1000
Solution
When we compute the sum, we will divide the sum into 2 parts: sum without carry and carry.
Sum without carry is one of the definitions of XOR, so we can directly use it.
To compute carry, we can first find which part is about to produce carry via AND, and use LEFT SHIFT 1 position to stimulate carry.
Now, the next step is to compute the sum of sum without carry and carry, which makes the problem a recursion.
Code
This problem is better written in C++ because integers in Python have unlimited digits, which is a trouble for us to stimulate plus operation in binary operations.
class Solution {
public:
int getSum(int a, int b) {
for(int sum_wo_carry, carry; b; a=sum_wo_carry, b=carry){
sum_wo_carry = a^b;
carry = (a&b)<<1;
}
return a;
}
};
756

被折叠的 条评论
为什么被折叠?



