Sum of Two Integers - Problem

You're given two integers a and b, and your task is to return their sum without using the addition (+) or subtraction (-) operators.

This is a classic bit manipulation problem that challenges you to think at the binary level. Instead of relying on built-in arithmetic operators, you'll need to simulate addition using bitwise operations - the same way computers actually perform addition at the hardware level!

Goal: Calculate a + b using only bitwise operators like AND (&), OR (|), XOR (^), and bit shifting.

Example: If a = 1 and b = 2, return 3. But remember - no + or - allowed!

Input & Output

example_1.py โ€” Basic Addition
$ Input: a = 1, b = 2
โ€บ Output: 3
๐Ÿ’ก Note: 1 + 2 = 3. In binary: 001 + 010 = 011. XOR gives 011, AND gives 000 (no carries), so result is 3.
example_2.py โ€” Addition with Carries
$ Input: a = 3, b = 5
โ€บ Output: 8
๐Ÿ’ก Note: 3 + 5 = 8. In binary: 011 + 101. XOR: 110, AND<<1: 010. Next: 110^010=100, (110&010)<<1=100. Next: 100^100=000, (100&100)<<1=1000. Result: 1000 = 8.
example_3.py โ€” Negative Numbers
$ Input: a = -1, b = 1
โ€บ Output: 0
๐Ÿ’ก Note: -1 + 1 = 0. Using two's complement representation, the carries eventually cancel out to produce zero.

Visualization

Tap to expand
Computer Addition Circuit SimulationXORSum GateANDCarry GateSHIFTLEFTPositionExample: 3 + 5 = 8Iteration 1: 011 (3)^ 101 (5) โ†’ 110 011 (3)& 101 (5) โ†’ 001 โ†’ 010Iteration 2: 110^ 010 โ†’ 100 110& 010 โ†’ 010 โ†’ 100Iteration 3: 100^ 100 โ†’ 000 100& 100 โ†’ 100 โ†’ 1000Final:000 ^ 1000 = 1000 = 8 โœ“Circuit Logicโ€ข XOR finds different bitsโ€ข AND finds carry positionsโ€ข SHIFT moves carries leftโ€ข Repeat until no carries
Understanding the Visualization
1
Convert to Binary
Express both numbers in binary format (001, 010)
2
XOR for Partial Sum
XOR operation gives us the sum ignoring any carry bits
3
AND+SHIFT for Carries
AND finds where carries occur, left shift moves them to next position
4
Repeat Until No Carries
Continue the process until carry becomes zero
Key Takeaway
๐ŸŽฏ Key Insight: This is exactly how your computer's ALU (Arithmetic Logic Unit) performs addition - no magic + operator, just clever bit manipulation!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(log(max(|a|, |b|)))

In worst case, we iterate once for each bit position, which is logarithmic in the maximum value

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using a constant amount of extra variables

n
2n
โœ“ Linear Space

Constraints

  • -1000 โ‰ค a, b โ‰ค 1000
  • No use of + or - operators allowed
  • Must handle negative numbers correctly using two's complement
Asked in
Apple 45 Microsoft 38 Amazon 32 Google 28
87.6K Views
High Frequency
~15 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen