8.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "strings"
  6. )
  7. func myAtoi(str string) int {
  8. str = strings.Trim(str, " ")
  9. if len(str) == 0 {
  10. return 0
  11. }
  12. chars := []rune(str)
  13. beg, end := 0, 0
  14. isNegative := false
  15. // judge the sign of the integer
  16. switch chars[beg] {
  17. case '-':
  18. isNegative = true
  19. fallthrough
  20. case '+':
  21. beg, end = 1, 1
  22. // deal with "+" or "-"
  23. if len(str) == 1 {
  24. return 0
  25. }
  26. default:
  27. beg, end = 0, 0
  28. }
  29. // find the first non-zero digit and the last valid digit
  30. for ; end <= len(chars); end++ {
  31. if chars[beg] == '0' {
  32. beg++
  33. // for str like "000000000000", return 0
  34. if beg == len(chars) {
  35. return 0
  36. }
  37. continue
  38. }
  39. if end == len(chars) || chars[end] < '0' || '9' < chars[end] {
  40. break
  41. }
  42. }
  43. if beg == end {
  44. // no valid digit
  45. return 0
  46. } else if end-beg > 10 { // overflow (MaxInt32 & MinInt32 have 10 digits only)
  47. if isNegative {
  48. return math.MinInt32
  49. }
  50. return math.MaxInt32
  51. }
  52. sum, base := int64(0), int64(1)
  53. for ; end > beg; end-- {
  54. num := int64(chars[end-1] - '0')
  55. sum += num * base
  56. base *= int64(10)
  57. }
  58. if isNegative {
  59. sum *= int64(-1)
  60. }
  61. if sum < math.MinInt32 {
  62. return math.MinInt32
  63. } else if sum > math.MaxInt32 {
  64. return math.MaxInt32
  65. }
  66. return int(sum)
  67. }
  68. func testMyAtoi(str string) {
  69. fmt.Printf("\"%s\" -> %d\n", str, myAtoi(str))
  70. }
  71. /* func main() {
  72. testMyAtoi("")
  73. testMyAtoi(" 00000000000000000000 ")
  74. testMyAtoi("+")
  75. testMyAtoi(" -0.1 ")
  76. testMyAtoi(" +1.1 ")
  77. testMyAtoi(" 234.1 ")
  78. testMyAtoi("42")
  79. testMyAtoi("9223372036854775808")
  80. testMyAtoi(" -2.1 ")
  81. testMyAtoi(" - 0.1 ")
  82. testMyAtoi(" num 0.1 ")
  83. } */