Bit Manipulation
75. Sum of Two Integers
Given two integers a and b, return the sum of the two integers without using the operators + and -.
Examples
Example 1
Input: a = 1, b = 2
Output: 3
Example 2
Input: a = 2, b = 3
Output: 5
Constraints
- -1000 <= a, b <= 1000
a: int
b: int
a, b = 3, 5
mask: int = 0xFFFFFFFF
while (b & mask) != 0:
tmp: int = (a & b) << 1
a = a ^ b
b = tmp
if a > 0x7FFFFFFF:
a = ~(a ^ mask)
print(a)
# <fixed>
# With negative numbers this entered an infinite loop because Python has arbitrary-precision
# integers and negative bits grow without bound. A 32-bit mask (0xFFFFFFFF) was added
# to simulate 32-bit integer overflow. Keyboard shortcuts
← h Previous problem
→ l Next problem
Esc Back to index
? Toggle this help