website/content.en/ChapterFour/0300~0399/0371.Sum-of-Two-Integers.md
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
Calculate the sum of two integers a and b without using the operators + and -.
a+b without using the addition and subtraction operators. This problem requires using the properties of the ^ and & operators. The ^ of two numbers can implement binary addition of two numbers without carry. Since addition needs to be implemented here, carry is definitely needed. So how to find the carry is the key to this problem.a & b is 0, no carry is needed; when it is 1, it means a carry is needed. The carry moves forward by one bit, so a left shift operation is also needed. Therefore, the carry to be added is (a&b)<<1.
package leetcode
func getSum(a int, b int) int {
if a == 0 {
return b
}
if b == 0 {
return a
}
// (a & b)<<1 calculates the carry
// a ^ b calculates addition without carry
return getSum((a&b)<<1, a^b)
}