To implement these operations using only the + operator, and suppose we have 2 numbers a, b:
Multiplication:
Multiplication can be implemented using repeated addition.
For example, 5 * 3 is 5 + 5 + 5.
Subtraction:
Use addition by negating the number being subtracted.
For example, 10 - 4 can be thought of as 10 + (-4).
Negation:
To implement negation, repeatedly add -1 to zero until the number is reached.
Division:
Division can be implemented by repeated subtraction (which uses addition). a / b can be implemented as finding how many times you need to add b, until getting a.
publicclassSolution {
publicintnegate(int x) {
int neg = 0;
int d = x > 0 ?-1 : 1;
while (x != 0) {
neg += d;
x += d;
}
return neg;
}
publicintsubtract(int a, int b) {
return a + negate(b);
}
publicintmultiply(int a, int b) {
if (a < b) {
return multiply(b, a);
}
int sum = 0;
for (int i = 0; i < Math.abs(b); i++) {
sum += a;
}
if (b < 0) {
sum = negate(sum);
}
return sum;
}
publicintdivide(int a, int b) {
if (b == 0) {
thrownew ArithmeticException("Cannot divide by zero");
}
int absA = Math.abs(a);
int absB = Math.abs(b);
int quotient = 0;
int sum = 0;
while (sum + absB <= absA) {
sum += absB;
quotient++;
}
if ((a > 0 && b < 0) || (a < 0 && b > 0)) {
quotient = negate(quotient);
}
return quotient;
}
}
classSolution:
defnegate(self, x: int) -> int:
neg =0 delta =-1if x >0else1while x !=0:
neg += delta
x += delta
return neg
defsubtract(self, a: int, b: int) -> int:
return a + self.negate(b)
defmultiply(self, a: int, b: int) -> int:
if a < b:
return self.multiply(b, a)
sum: int =0for _ in range(abs(b)):
sum += a
if b <0:
sum = self.negate(sum)
return sum
defdivide(self, a: int, b: int) -> int:
if b ==0:
raiseArithmeticError("Cannot divide by zero")
absA = abs(a)
absB = abs(b)
quotient: int =0 sum: int =0while sum + absB <= absA:
sum += absB
quotient +=1if (a >0and b <0) or (a <0and b >0):
quotient = self.negate(quotient)
return quotient