题意:
解题思路:
思路:
1. 模拟 + 倍增
2. 标记正负号,然后转成绝对值进行操作
3. dividend=11,divisor=3
4. (3 + 3 = 6 < 11) => 得出最少有2个3,所以倍数为2
5. 6 + 6 > 11,但是11 - 6 = 5,5大于3,得出最少可得1个3
PHP代码实现:
class Solution {
function divide($dividend, $divisor) {
$sign = 1;
if (($dividend > 0 && $divisor < 0)
|| ($dividend < 0 && $divisor > 0)) $sign = -1;
$ldivedend = abs($dividend);
$ldivisor = abs($divisor);
if ($ldivedend < $ldivisor || $ldivedend == 0) return 0;
$lres = $this->div($ldivedend, $ldivisor);
$num = $sign < 1 ? 0 - $lres : $lres;
if ($num > pow(2, 31) - 1) return pow(2, 31) - 1;
if ($num < pow(-2, 31)) return pow(-2, 31);
return $num;
}
function div($ldivedend, $ldivisor) {
if ($ldivedend < $ldivisor) return 0;
$sum = $ldivisor;
$mult = 1;
while (($sum + $sum) < $ldivedend) {
$sum += $sum;
$mult += $mult;
}
return $mult + $this->div($ldivedend - $sum, $ldivisor);
}
}
GO代码实现:
func divide(dividend int, divisor int) int {
if dividend == math.MinInt32 && divisor == -1 {
return math.MaxInt32
}
sign := 1
if (divisor > 0 && dividend < 0) || (divisor < 0 && dividend > 0) {
sign = -1
}
if divisor < 0 { divisor *= -1 }
if dividend < 0 { dividend *= -1 }
res := div(int64(dividend), int64(divisor))
if sign == -1 {
return -res
}
return res
}
func div(a int64,b int64) int {
if a < b {
return 0
}
sum := b
mul := 1
for (sum + sum) < a {
sum += sum
mul += mul
}
return mul + div(a - sum, b)
}