Problem

Implement a function Add(a, b) that returns the sum of two integers without using the arithmetic + operator (or any direct arithmetic increment/decrement). Use bitwise operations to produce the result.

This is very similar to Sum of Two Integers, but here - operator is allowed.

Examples

Example 1

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

Example 2

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

Solution

Method 1 — Bitwise addition (half-adder style)

We can use half adder solution - Sum of two numbers using only bitwise operators.

Method 2 — Using subtraction and negation

Intuition

Adding b to a is equivalent to subtracting the negation of b from a: a + b = a - (-b). If the problem constraint only forbids the + operator (and not - or unary negation), this identity gives a very short alternative.

Approach

  1. Compute neg_b = -b using the language’s unary negation.
  2. Return a - neg_b.

Edge cases:

  • This uses the subtraction operator; if the problem forbids all arithmetic operators then this method is not allowed.
  • Be cautious of overflow in fixed-width integer types when negating the most-negative value (e.g., INT_MIN).

Code

1
2
3
4
5
6
7
class Solution {
 public:
  static int add(int a, int b) {
    int neg_b = -b;
    return a - neg_b;
  }
};
1
2
3
4
5
6
package main

func Add(a, b int) int {
  negB := -b
  return a - negB
}
1
2
3
4
5
6
class Solution {
  public static int add(int a, int b) {
    int negB = -b;
    return a - negB;
  }
}
1
2
3
4
5
class Solution:
    @staticmethod
    def add(a: int, b: int) -> int:
        neg_b = -b
        return a - neg_b

Complexity

  • ⏰ Time complexity: O(1) — constant time arithmetic operations.
  • 🧺 Space complexity: O(1) extra space.