1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| func myAtoi(s string) int { const MinInt32, MaxInt32 = -1 << 31, 1<<31 - 1 states := map[string][]string{ "start": {"start", "signed", "number", "end"}, "signed": {"end", "end", "number", "end"}, "number": {"end", "end", "number", "end"}, "end": {"end", "end", "end", "end"}, }
state := "start" ans := 0 sign := 1
for i := 0; i < len(s); i++ { index := get_state(s, i) curr := states[state][index]
switch curr { case "end": return ans * sign case "number": ans = ans*10 + int(s[i]) - 48 if ans * sign >= MaxInt32 { return MaxInt32 } if ans * sign <= MinInt32 { return MinInt32 } case "signed": if s[i] == '-' { sign = -1 } }
state = curr
}
return ans * sign }
func get_state(s string, i int) int { switch { case s[i] == ' ': return 0 case s[i] == '+' || s[i] == '-': return 1 case s[i] >= '0' && s[i] <= '9': return 2 } return 3 }
|