请实现整数数字的乘法、减法和除法运算,运算结果均为整数数字,程序中只允许使用加法运算符和逻辑运算符,允许程序中出现正负常数,不允许使用位运算。
你的实现应该支持如下操作:
Operations()
构造函数minus(a, b)
减法,返回a - b
multiply(a, b)
乘法,返回a * b
divide(a, b)
除法,返回a / b
示例:
Operations operations = new Operations();
operations.minus(1, 2); //返回-1
operations.multiply(3, 4); //返回12
operations.divide(5, -2); //返回-2
提示:
- 你可以假设函数输入一定是有效的,例如不会出现除法分母为0的情况
- 单个用例的函数调用次数不会超过1000次
class Operations {
public Operations() {
}
public int minus(int a, int b) {
return a + negate(b);
}
public int multiply(int a, int b) {
int mul = 0;
int initialDelta = b > 0 ? -1 : 1;
int initialMultiplyDelta = b < 0 ? negate(a) : a;
int multiplyDelta = initialMultiplyDelta, delta = initialDelta;
while (b != 0) {
if (isOverflow(b, b + delta)) {
delta = initialDelta;
multiplyDelta = initialMultiplyDelta;
}
b += delta;
mul += multiplyDelta;
delta += delta;
multiplyDelta += multiplyDelta;
}
return mul;
}
public int divide(int a, int b) {
int div = 0;
int initialDelta = a > 0 == b > 0 ? 1 : -1;
int initialDivideDelta = a > 0 == b > 0 ? negate(b) : b;
int delta = initialDelta, divideDelta = initialDivideDelta;
while (a != 0) {
if (isOverflow(divideDelta, initialDivideDelta)
|| isOverflow(a, a + divideDelta)) {
if (isOverflow(a, a + initialDivideDelta)) {
break;
}
delta = initialDelta;
divideDelta = initialDivideDelta;
}
div += delta;
a += divideDelta;
delta += delta;
divideDelta += divideDelta;
}
return div;
}
private int negate(int x) {
int negation = 0;
int initialDelta = x > 0 ? 1 : -1;
int delta = initialDelta;
while (x != 0) {
if (isOverflow(x, x + delta)) {
delta = initialDelta;
}
x += delta;
negation += delta;
delta += delta;
}
return negation;
}
private boolean isOverflow(int source, int target) {
return target != 0 && target > 0 != source > 0;
}
}