funcmyAtoi(str string)int { var ( f int numStr string num int k int ) for { iflen(str) < 1 { return0 } ch := str[0] if ch == 32 { str = str[1:] } else { break } } ch := str[0] if ch == 45 { str = str[1:] f = -1 } elseif ch == 43 { str = str[1:] f = 1 } elseif ch >= 48 && ch <= 57 { f = 1 } else { f = 0 } if f == 0 { return0 } else { for index := 0; index < len(str); index++ { if str[index] >= 48 && str[index] <= 57 { numStr += string(str[index]) } else { break } } } newNumLength := len(numStr) for index := 0; index < newNumLength; index++ { if k != 0 { num *= 10 } num += int(numStr[index]) - 48 k++ if num*f >= 2147483648 { return2147483647 } if num*f < -2147483648 { return-2147483648 } } num = num * f return num }
本地测试
package main
import ( "fmt" )
funcmain() { s := "42" fmt.Println(myAtoi(s), 42) s = " " fmt.Println(myAtoi(s), 0) s = " " fmt.Println(myAtoi(s), 0) s = "" fmt.Println(myAtoi(s), 0) s = "-42" fmt.Println(myAtoi(s), -42) s = " -42" fmt.Println(myAtoi(s), -42) s = "+42" fmt.Println(myAtoi(s), 42) s = "0" fmt.Println(myAtoi(s), 0) s = "9" fmt.Println(myAtoi(s), 9) s = "4193 with words" fmt.Println(myAtoi(s), 4193) s = "words and 987" fmt.Println(myAtoi(s), 0) s = "-91283472332" fmt.Println(myAtoi(s), -2147483648) s = "2147483648" fmt.Println(myAtoi(s), 2147483647) s = "9223372036854775808" fmt.Println(myAtoi(s), 2147483647) }