LeetCode 371: Sum Of Two Integers — Step-by-Step Visual Trace
Medium — Bit Manipulation | Math
The Problem
Calculate the sum of two integers without using the + or - operators, implementing addition using only bitwise operations.
Approach
Uses XOR to compute sum without carry, AND with left shift to compute carry, and iterates until no carry remains. Handles negative numbers with bit masking and two’s complement conversion.
Time: O(log n) · Space: O(1)
Code
class Solution:
def getSum(self, a: int, b: int) -> int:
MASK = 0xFFFFFFFF
MAX_INT = 0x7FFFFFFF
while b != 0:
a, b = (a ^ b) & MASK, ((a & b) << 1) & MASK
return a if a <= MAX_INT else ~(a ^ MASK)
Watch It Run
Try it yourself: Open TraceLit and step through every line.
Built with TraceLit — the visual algorithm tracer for LeetCode practice.
Comments