Sum of Two Integers

Binary
Medium

Approach

Diagrams

Analysis

Time

O(1)

Space

O(1)
class Solution:
    def getSum(self, a, b):
        if a == 0:
            return b

        if b == 0:
            return a

        mask = 0xffffffff

        while b != 0:
            a, b = (a ^ b) & mask, ((a & b) << 1) & mask

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

Learn

#Bit Manipulation

Videos