TIC
The Interns Company

Sum of Two Integers

MediumAcceptance: 50.7%

Problem Statement

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

Constraints:

  • -1000 <= a, b <= 1000

Input Format:

  • Two integers a and b

Output Format:

  • Return the sum of a and b

Examples:

Example 1:

Input:

a = 1, b = 2

Output:

3

Explanation:

1 + 2 = 3

Example 2:

Input:

a = 2, b = 3

Output:

5

Explanation:

2 + 3 = 5

Example 3:

Input:

a = -1, b = 1

Output:

0

Explanation:

-1 + 1 = 0

Solutions

Bitwise Operations Approach

Time: O(1)
Space: O(1)

Use bitwise operations to simulate binary addition without using + or -. XOR to find the sum without carry, AND with left shift to find the carry, and repeat until carry is 0.

Recursive Approach

Time: O(1)
Space: O(1)

Same bitwise operations approach but implemented recursively. The base case is when there's no carry (b = 0).

Algorithm Walkthrough

Example input: nums = []

Step-by-step execution:

  1. a = 2 (binary 10), b = 3 (binary: 11)
  2. XOR of a and b: 2 ^ 3 = 1 (binary: 01) (sum without carry)
  3. AND with shift: (2 & 3) << 1 = (10 & 11) << 1 = (10) << 1 = 100 = 4 (carry)
  4. Next iteration: a = 1, b = 4
  5. XOR of a and b: 1 ^ 4 = 5 (binary: 101) (sum without carry)
  6. AND with shift: (1 & 4) << 1 = (01 & 100) << 1 = (0) << 1 = 0 (no carry)
  7. Since there's no carry left, return a = 5

Hints

Hint 1
Think about how addition works at the bit level. What happens when you have 1 + 1?
Hint 2
Consider using bitwise operations: XOR (^) and AND (&) with left shift (<<).
Hint 3
XOR gives you the sum without carrying bits, AND with shift gives you the carry.
Hint 4
Repeat the process until there's no carry left.

Video Tutorial

Video tutorials can be a great way to understand algorithms visually

Visualization

Visualize the bitwise operations step by step, showing how the binary representation changes in each iteration.

Key visualization elements:

  • current bits
  • XOR operation
  • AND with shift
  • carry calculation

Implementation Notes

This problem tests understanding of bitwise operations and binary addition. The key insight is to separate the addition process into two parts: the sum without carry (XOR) and the carry (AND with shift).