Sum of Two Integers - Problem

Given two integers a and b, return the sum of the two integers without using the operators + and -.

This problem requires you to implement addition using only bitwise operations. You'll need to think about how addition works at the binary level and simulate the process of adding two numbers bit by bit.

Hint: Consider how XOR and AND operations can help simulate addition and carry operations.

Input & Output

Example 1 — Basic Addition
$ Input: a = 1, b = 2
Output: 3
💡 Note: 1 + 2 = 3. Using bitwise: 1 (001) XOR 2 (010) = 3 (011), no carry needed.
Example 2 — With Carry
$ Input: a = 2, b = 3
Output: 5
💡 Note: 2 + 3 = 5. Binary: 010 + 011. XOR gives 001, carry is (010 & 011) << 1 = 100. Then 001 + 100 = 101 (5).
Example 3 — Negative Numbers
$ Input: a = -1, b = 1
Output: 0
💡 Note: -1 + 1 = 0. The bitwise operations handle two's complement representation correctly.

Constraints

  • -1000 ≤ a, b ≤ 1000

Visualization

Tap to expand
Sum of Two Integers Without + or - OperatorsInputa = 1, b = 2Bitwise Addition Process1. XOR: 001 ^ 010 = 011 (sum without carry)2. AND+Shift: (001 & 010) << 1 = 000 (carry)3. Carry = 0, so we're done!OutputResult = 3Key Insight: Binary Addition Logic• XOR gives sum bits (1+0=1, 0+1=1, 0+0=0, 1+1=0)• AND+Shift gives carry bits (only 1+1 produces carry)🎯 Time: O(1), Space: O(1) - No + or - operators used!
Understanding the Visualization
1
Input
Two integers a=1, b=2
2
Process
Use XOR and AND with bit shifting
3
Output
Sum = 3
Key Takeaway
🎯 Key Insight: XOR handles sum without carry, AND+shift handles carry propagation
Asked in
Google 25 Amazon 30 Facebook 20 Microsoft 15
32.0K Views
Medium Frequency
~15 min Avg. Time
890 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