题解
设未知数: Br= 125 / 3,拆进行如下拆解:
- Br = 125 / 3
- Br = (29 + 96)/3
- Br = 29/3 + (32 * 3) / 3
- Br = 29/3 + (2 * 2 * 2 * 2 * 2 * 3) / 3
- Br = (5 + 24) / 3 + (2 * 2 * 2 * 2 * 2 * 3) / 3
- Br = 5/3 + (8 * 3) /3 + (2 * 2 * 2 * 2 * 2 * 3) / 3
- Br = (2 + 3)/3 + (2 * 2 * 2 * 3)/3 + (2 * 2 * 2 * 2 * 2 * 3) / 3
- Br = 2/3 + (1 * 3)/3 + (2 * 2 * 2 * 3)/3 + (2 * 2 * 2 * 2 * 2 * 3) / 3
- Br = 0 + 1 + 8 + 32
- Br = 41
看到这个表达式的推演,那么我们可以使用递归进行求解了
-
为了方便计算,把除数与被除数取为负数
-
为了判断溢出,把最小负数(int)绝对值的一半定义为静态变量:halfMax = -1073741824; 当某个数大于它时二倍必定溢出
代码
class Solution {
/** 最小负数绝对值的一半 */
private static final int halfMax = -1073741824;
public int divide(int dividend, int divisor) {
if (divisor == 1) return dividend;
if (divisor == -1) return dividend == Integer.MIN_VALUE ? Integer.MAX_VALUE : -dividend;
/** 两数异号:位与大于0,位或小于0 */
boolean diff = (dividend < 0 && divisor >0) || (dividend > 0 && divisor < 0);
/** 取为负 */
dividend = dividend > 0 ? -dividend : dividend;
divisor = divisor > 0 ? -divisor : divisor;
if (dividend > divisor) return 0;
int result = deepDivide(dividend, divisor, divisor, 1);
return diff ? -result : result;
}
private int deepDivide(int dividend, int divisor, int curr, int result){
if (dividend > divisor) return 0;
int dCurr = curr + curr;
if (dCurr < dividend || curr < halfMax) {
int btn = dividend - curr;
if (btn > divisor){
return result;
}
/** 被除数与当前值差值递归 */
return result + deepDivide(btn, divisor, divisor, 1);
} else {
result += result;
if (dCurr == dividend){
return result;
} else {
/** 被除数与当前值二倍差值递归 */
return deepDivide(dividend, divisor, dCurr, result);
}
}
}
}