题意:

image.png

解题思路:

  1. 思路:
  2. 1. 模拟 + 倍增
  3. 2. 标记正负号,然后转成绝对值进行操作
  4. 3. dividend=11divisor=3
  5. 4. (3 + 3 = 6 < 11) => 得出最少有23,所以倍数为2
  6. 5. 6 + 6 > 11,但是11 - 6 = 55大于3,得出最少可得13

PHP代码实现:

  1. class Solution {
  2. function divide($dividend, $divisor) {
  3. $sign = 1;
  4. if (($dividend > 0 && $divisor < 0)
  5. || ($dividend < 0 && $divisor > 0)) $sign = -1;
  6. $ldivedend = abs($dividend);
  7. $ldivisor = abs($divisor);
  8. if ($ldivedend < $ldivisor || $ldivedend == 0) return 0;
  9. $lres = $this->div($ldivedend, $ldivisor);
  10. $num = $sign < 1 ? 0 - $lres : $lres;
  11. if ($num > pow(2, 31) - 1) return pow(2, 31) - 1;
  12. if ($num < pow(-2, 31)) return pow(-2, 31);
  13. return $num;
  14. }
  15. function div($ldivedend, $ldivisor) {
  16. if ($ldivedend < $ldivisor) return 0;
  17. $sum = $ldivisor;
  18. $mult = 1;
  19. while (($sum + $sum) < $ldivedend) {
  20. $sum += $sum;
  21. $mult += $mult;
  22. }
  23. return $mult + $this->div($ldivedend - $sum, $ldivisor);
  24. }
  25. }

GO代码实现:

  1. func divide(dividend int, divisor int) int {
  2. if dividend == math.MinInt32 && divisor == -1 {
  3. return math.MaxInt32
  4. }
  5. sign := 1
  6. if (divisor > 0 && dividend < 0) || (divisor < 0 && dividend > 0) {
  7. sign = -1
  8. }
  9. if divisor < 0 { divisor *= -1 }
  10. if dividend < 0 { dividend *= -1 }
  11. res := div(int64(dividend), int64(divisor))
  12. if sign == -1 {
  13. return -res
  14. }
  15. return res
  16. }
  17. func div(a int64,b int64) int {
  18. if a < b {
  19. return 0
  20. }
  21. sum := b
  22. mul := 1
  23. for (sum + sum) < a {
  24. sum += sum
  25. mul += mul
  26. }
  27. return mul + div(a - sum, b)
  28. }