Given two integers x and y, compute x - y without using the arithmetic subtraction operator (-). Use bitwise operators and shifts only, and preserve two’s-complement semantics for negative numbers.
This problem is a small variant of the addition-without-+ trick (LeetCode 371). Subtraction can be reduced to addition by using two’s complement: x - y == x + (-y) where -y == ~y + 1.
We present two concise approaches: (A) use an add routine that uses XOR/AND+shift to compute sum+carry iteratively, then compute x + (~y + 1), and (B) directly perform the iterative subtraction-like step using XOR and borrow propagation.
In two’s-complement arithmetic, negation is ~y + 1. So subtraction x - y equals x + (~y + 1). Implement add(a, b) using bitwise XOR for sum and bitwise AND/shift for carry, and reuse it for subtraction.
classSolution {
public:staticint add(int a, int b) {
while (b !=0) {
int sum = a ^ b;
int carry = (a & b) <<1;
a = sum;
b = carry;
}
return a;
}
staticintsubtract(int x, int y) {
int neg_y = add(~y, 1);
return add(x, neg_y);
}
};
classSolution {
publicstaticintadd(int a, int b) {
while (b != 0) {
int sum = a ^ b;
int carry = (a & b) << 1;
a = sum;
b = carry;
}
return a;
}
publicstaticintsubtract(int x, int y) {
int negY = add(~y, 1);
return add(x, negY);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
@staticmethoddefadd(a: int, b: int) -> int:
while b !=0:
s = a ^ b
carry = (a & b) <<1 a = s
b = carry
return a
@staticmethoddefsubtract(x: int, y: int) -> int:
neg_y = Solution.add(~y, 1)
return Solution.add(x, neg_y)
This method uses the same idea as addition without + but propagates borrows instead of carries. The recurrence x' = x ^ y, y' = (~x & y) << 1 repeatedly removes borrow bits until y == 0 and x contains the result.
For languages with unbounded integers (Python) the same code works and semantics match mathematical integers; for fixed-width languages be mindful of overflow and signed shifts.