Problem

Given two integers a and b, compute a - b using only the plus operator (+). You may not use the subtraction operator (-). The goal is to show how to obtain the negative of a number using additions only, then compute the result as a + (-b).

Examples

Example 1

1
2
Input: a = 10, b = 4
Output: 6

Example 2

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

Solution

Method 1 — Negation by repeated increment/decrement (use + only)

Intuition

To compute a - b using only +, observe that a - b == a + (-b). So the problem reduces to computing -b by using additions only. We can repeatedly add +1 or -1 (implemented by adding the integer 1 or repeatedly adding +1 when we need to move toward zero) to b while simultaneously building up the negated value until b becomes zero.

For example, to negate 5, start from neg = 0 and repeatedly add -1 (which we implement by adding +(-1) conceptually) to both neg and b until b == 0. The result neg becomes -5.

Approach

  1. Determine the step value to move b toward zero: if b > 0 then step = -1 else step = +1.
  2. Initialize neg = 0.
  3. While b != 0:
    • neg = neg + step (accumulate the negated value)
    • b = b + step (move b toward zero)
  4. After the loop, neg equals -original_b.
  5. Return a + neg as the final result.

Edge cases:

  • If b == 0, simply return a.
  • This method performs |b| iterations; for very large |b| it is slow and may be impractical in fixed-time settings.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  static int negate(int x) {
    int neg = 0;
    int step = x > 0 ? -1 : 1;
    while (x != 0) {
      neg += step;
      x += step;
    }
    return neg;
  }

  static int subtract(int a, int b) {
    return a + negate(b);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

func Negate(x int) int {
  neg := 0
  step := 1
  if x > 0 {
    step = -1
  }
  for x != 0 {
    neg += step
    x += step
  }
  return neg
}

func Subtract(a, b int) int {
  return a + Negate(b)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public static int negate(int x) {
    int neg = 0;
    int step = x > 0 ? -1 : 1;
    while (x != 0) {
      neg += step;
      x += step;
    }
    return neg;
  }

  public static int subtract(int a, int b) {
    return a + negate(b);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    @staticmethod
    def negate(x: int) -> int:
        neg = 0
        step = -1 if x > 0 else 1
        while x != 0:
            neg += step
            x += step
        return neg

    @staticmethod
    def subtract(a: int, b: int) -> int:
        return a + Solution.negate(b)

Complexity

  • ⏰ Time complexity: O(|b|), because the algorithm performs one loop iteration per unit magnitude of b.
  • 🧺 Space complexity: O(1), only a few integer temporaries are used.