11.8 Sum of Two Integers

11.8.1 Problem Metadata

11.8.2 Description

Calculate the sum of two integers a and b without using the + or - operators.

11.8.3 Examples

Input: a = 1, b = 2
Output: 3

11.8.4 Constraints

  • -1000 <= a, b <= 1000

11.8.5 Solution - Bitwise Addition

11.8.5.1 Walkthrough

Sum without carry is a ^ b; carry bits are (a & b) << 1. Iteratively propagate carry until it is zero.

11.8.5.2 Analysis

  • Time Complexity: O(1) for fixed-width integers
  • Space Complexity: O(1)

11.8.5.3 Implementation Steps

  1. While b != 0, compute carry = (a & b) << 1 and a = a ^ b.
  2. Set b = carry.
  3. a becomes the final sum.

11.8.5.4 Code - Java

public int getSum(int a, int b) {
    while (b != 0) {
        int carry = (a & b) << 1;
        a = a ^ b;
        b = carry;
    }
    return a;
}