Skip to content

Latest commit

 

History

History
34 lines (25 loc) · 620 Bytes

File metadata and controls

34 lines (25 loc) · 620 Bytes

Question:

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

Analysis

不让用加减,就是用逻辑计算了,异或(^)等于不考虑进位后的加减,与(&)等于只保留进位的结果,那最终结果就是(不进位结果 + 进位结果<<1)

不让用+,则可以用递归解决不得不的+

Tips

Code

func getSum(a int, b int) int {
    if b == 0 {
        return a
    }
    return getSum(a ^ b, (a & b) << 1)
}