29.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package main
  2. import (
  3. "math"
  4. )
  5. /* func abs(x int) int {
  6. if x < 0 {
  7. return -x
  8. }
  9. return x
  10. } */
  11. // time out
  12. func divideOld(dividend int, divisor int) int {
  13. if divisor == 0 {
  14. return math.MaxInt32
  15. }
  16. var cnt, incr int64 = 0, 1
  17. if (dividend&(1<<32))^(divisor&(1<<32)) != 0 {
  18. incr = -1
  19. }
  20. dividend, divisor = abs(dividend), abs(divisor)
  21. for dividend >= divisor {
  22. dividend -= divisor
  23. cnt += incr
  24. }
  25. if cnt < math.MinInt32 || cnt > math.MaxInt32 {
  26. return math.MaxInt32
  27. }
  28. return int(cnt)
  29. }
  30. func divide(dividend int, divisor int) int {
  31. sign := 1
  32. // 判断同号、异号
  33. if (dividend>>31)^(divisor>>31) != 0 {
  34. sign = -1
  35. }
  36. dividend, divisor = abs(dividend), abs(divisor)
  37. res := 0
  38. // x/y: x -= y * 2^31, res += 2^31, x -= y * 2^30, res += 2^30, ...
  39. for i := uint(32); i > 0; i-- {
  40. if divisor<<(i-1) > dividend {
  41. continue
  42. }
  43. dividend -= divisor << (i - 1)
  44. res += 1 << (i - 1)
  45. }
  46. res *= sign
  47. // overflow
  48. if res < math.MinInt32 || res > math.MaxInt32 {
  49. return math.MaxInt32
  50. }
  51. return res
  52. }
  53. /* func main() {
  54. fmt.Println(divide(-1, 1))
  55. fmt.Println(divide(-1, -1))
  56. fmt.Println(divide(-1<<31, -1))
  57. fmt.Println(divide(1, 1))
  58. fmt.Println(divide(535, 1))
  59. } */