The problem statement asks us to find the sum of two integers without using the +
or -
operators. This can be done using bitwise operations.
^
): This operation will handle the addition without carrying. For example, 5 ^ 3
results in 6
(binary 101 ^ 011 = 110
).&
and <<
): This will handle the carrying. For example, 5 & 3
results in 1
(binary 101 & 011 = 001
), and 1 << 1
results in 2
(binary 001 << 1 = 010
).We will:
Python handles arbitrarily large integers with its built-in int
type, but when simulating 32-bit integer behavior, we need to take special care of overflow:
0xFFFFFFFF
to get the last 32 bits.Let’s implement the solution with the above strategy.
def getSum(a: int, b: int) -> int:
# 32 bits integer max
MAX = 0x7FFFFFFF
# Mask to get last 32 bits
mask = 0xFFFFFFFF
while b != 0:
# calulate the carry
carry = (a & b) << 1
# add the bits without carry
a = (a ^ b) & mask
# apply the carry
b = carry & mask
# if a is negative, get its positive complement
if a > MAX:
a = ~(a ^ mask)
return a
# Example usage:
# a = 1, b = 2, expected output = 3
print(getSum(1, 2)) # Output: 3
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?