#371

Sum of Two Integers

Medium
MathBit ManipulationBit ManipulationMathematical Operations
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

Using bit manipulation, we can calculate the sum without using + or - by leveraging the properties of binary addition. This method is efficient and works in constant time.

⚙️

Algorithm

2 steps
  1. 1Step 1: While b is not zero, do the following: a. Calculate carry as (a & b) << 1. b. Update a to (a ^ b). c. Update b to carry.
  2. 2Step 2: When b becomes zero, return a as the sum.
solution.py11 lines
1# Full working Python code
2
3def get_sum(a, b):
4    while b != 0:
5        carry = a & b
6        a = a ^ b
7        b = carry << 1
8    return a
9
10# Example usage
11print(get_sum(1, 2))  # Output: 3

Complexity note: The time complexity is O(1) because the number of operations is constant, regardless of the size of the integers.

  • 1Bit manipulation can replace arithmetic operations.
  • 2Understanding binary representation is crucial for efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.