算法原链接

https://leetcode-cn.com/problems/string-to-integer-atoi/

解法

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "regexp"
  6. "strconv"
  7. "strings"
  8. )
  9. func main() {
  10. str := "9223372036854775808"
  11. //ii := 922337203685477580
  12. //fmt.Println(ii * 10 + 8)
  13. //i := myAtoi(str)
  14. //fmt.Println(i)
  15. i := myAtoi1(str)
  16. fmt.Println(i)
  17. }
  18. // 自己的解法,耗时很短,但是相对占内存一些
  19. func myAtoi(s string) int {
  20. reg := regexp.MustCompile(`^\s*[+-]?\d*`)
  21. result := reg.FindString(s)
  22. result = strings.Trim(result, " ")
  23. if len(result) == 0 {
  24. return 0
  25. }
  26. num, _ := strconv.Atoi(result)
  27. if num > math.MaxInt32 {
  28. return math.MaxInt32
  29. }
  30. if num < math.MinInt32 {
  31. return math.MinInt32
  32. }
  33. return num
  34. }
  35. // 这个解法参考了官方的自动机解法思路
  36. // 纯操作数字会导致数字溢出变成负数,所以用字符串拼接的方式再转数字
  37. func myAtoi1(s string) int {
  38. var i int
  39. //var flag = 1
  40. // start signed in_number end
  41. state := "start"
  42. str := ""
  43. for _, ch1 := range s {
  44. if state == "start" && ch1 == 32 {
  45. continue
  46. } else if state == "start" && (ch1 == 45 || ch1 == 43) {
  47. state = "signed"
  48. if ch1 == 45 {
  49. str = "-"
  50. }
  51. //else {
  52. // flag = 1
  53. //}
  54. } else if state != "end" && ch1 >= 48 && ch1 <= 57 {
  55. state = "in_number"
  56. //c1, _ := strconv.Atoi(string(ch1))
  57. //i = i*10 + c1
  58. str += string(ch1)
  59. } else {
  60. state = "end"
  61. break
  62. }
  63. }
  64. //i *= flag
  65. i, _ = strconv.Atoi(str)
  66. if i > math.MaxInt32 {
  67. return math.MaxInt32
  68. }
  69. if i < math.MinInt32 {
  70. return math.MinInt32
  71. }
  72. return i
  73. }