Problem statement

https://leetcode.com/problems/sum-of-two-integers/

Solution

This problem in fact can be quite difficult, if you did not solve it before. The trick is to use bit manipulations: on each iteration taking one bit from one number and put it to another.

Complexity

Complexity is O(32), because we can have 32 iterations. In python however we need to deal with negative numbers, because they stored differently.

Code

class Solution:
    def getSum(self, a, b):
        mask = 0xffffffff
        
        while b != 0:
            a, b = (a ^ b) & mask, ((a & b) << 1) & mask

        return ~(a ^ mask) if (a >> 31) & 1 else a