Subtract using plus operator only
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
Input: a = 10, b = 4
Output: 6
Example 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
- Determine the
stepvalue to movebtoward zero: ifb > 0thenstep = -1elsestep = +1. - Initialize
neg = 0. - While
b != 0:neg = neg + step(accumulate the negated value)b = b + step(movebtoward zero)
- After the loop,
negequals-original_b. - Return
a + negas the final result.
Edge cases:
- If
b == 0, simply returna. - This method performs
|b|iterations; for very large|b|it is slow and may be impractical in fixed-time settings.
Code
C++
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);
}
};
Go
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)
}
Java
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);
}
}
Python
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 ofb. - 🧺 Space complexity:
O(1), only a few integer temporaries are used.