29.go 1.2 KB

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