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).
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.
classSolution {
public:staticint negate(int x) {
int neg =0;
int step = x >0?-1:1;
while (x !=0) {
neg += step;
x += step;
}
return neg;
}
staticintsubtract(int a, int b) {
return a + negate(b);
}
};
classSolution {
publicstaticintnegate(int x) {
int neg = 0;
int step = x > 0 ?-1 : 1;
while (x != 0) {
neg += step;
x += step;
}
return neg;
}
publicstaticintsubtract(int a, int b) {
return a + negate(b);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
@staticmethoddefnegate(x: int) -> int:
neg =0 step =-1if x >0else1while x !=0:
neg += step
x += step
return neg
@staticmethoddefsubtract(a: int, b: int) -> int:
return a + Solution.negate(b)