Sum of Two Integers
Master this topic with zero to advance depth.
Sum of Two Integers
Given two integers a and b, return the sum of the two integers without using the operators + and -.
Examples
Level I: Brute Force (Bit-by-Bit Simulation)
Intuition
Simulate how a half-adder or full-adder works. Iterate through each bit position (0 to 31), calculate the sum of bits and the carry, and build the result bit by bit.
Thought Process
- Initialize
res = 0,carry = 0. - For
ifrom 0 to 31:- Get -th bits of
aandb. sum = bitA ^ bitB ^ carry.carry = (bitA & bitB) | (carry & (bitA ^ bitB)).- Set -th bit of
restosum.
- Get -th bits of
- Return
res.
Pattern: Simulation / Logic Gates
Level II: Recursive XOR & AND
Intuition
The iterative logic can be expressed recursively. The sum of a and b is equivalent to the XOR of a and b (sum without carry) plus the AND of a and b shifted left (the carry).
Level III: Optimal (Iterative XOR & AND)
Intuition
Addition can be broken into two parts: the sum without carry (a ^ b) and the carry itself ((a & b) << 1). We repeat this process until the carry becomes zero.
Thought Process
a ^ bgives the sum bits where no carry is involved.a & bgives the bits where a carry is generated.- Shift the carry left by 1 to add it to the next significant bit.
- Repeat until carry is 0.
Pattern: Recursive Addition Logic
Detailed Dry Run
a = 2 (10), b = 3 (11)
- Iteration 1: sum = 10 ^ 11 = 01 (1) carry = (10 & 11) << 1 = 100 (4)
- Iteration 2: sum = 001 ^ 100 = 101 (5) carry = (001 & 100) << 1 = 000 (0) Result: 5
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.