LeetCode 371 Sum of Two Integers - Example and Complexity Analysis

Walkthrough and analysis

Trace a = 2, b = 3 (binary: 10 and 11).

Iteration 1:

  • sum = 10 ^ 11 = 01.
  • carry = (10 & 11) << 1 = (10) << 1 = 100.
  • a = 01, b = 100.

Iteration 2:

  • sum = 001 ^ 100 = 101.
  • carry = (001 & 100) << 1 = (000) << 1 = 000.
  • a = 101, b = 000.

b = 0. Done. Answer: 101 = 55.

O(1)O(1) time (at most 32 iterations for 32-bit integers). O(1)O(1) space.