DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

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)
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)