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 - Bitwise Addition INPUT a = 1 (decimal) Binary: 0 0 0 1 b = 2 (decimal) Binary: 0 0 1 0 Bit Representation: 0 0 0 1 a = 1 0 0 1 0 b = 2 ALGORITHM STEPS 1 XOR for sum bits a XOR b = 0001 XOR 0010 Result: 0011 (3) 2 AND for carry bits a AND b = 0001 AND 0010 Result: 0000 (0) 3 Shift carry left carry = (a AND b) << 1 Result: 0000 (0) 4 Check carry If carry != 0, repeat carry=0, done! Operation Table 0001 (a=1) ^ 0010 (b=2) = 0011 (XOR=3) carry: 0 (done) FINAL RESULT Binary Result: 0 0 1 1 0011 in binary Output: 3 Verification: 1 + 2 = 3 [OK] Complexity: Time: O(1) Space: O(1) Key Insight: XOR (^) simulates addition without carry: 1^0=1, 0^1=1, 1^1=0, 0^0=0 AND (&) finds where carries occur, then shift left (<<1) to position them. Repeat until no carry remains. This mimics how hardware adders work at the circuit level! TutorialsPoint - Sum of Two Integers | Optimal Bitwise Solution
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