@@ -18,13 +18,12 @@ var ascii = map[int32]int{
18
18
'9' : 9 ,
19
19
}
20
20
21
- func myAtoi (str string ) int {
22
- // 4 ms, 2.3 MB
23
- signed := ""
24
- temp , res := "" , 0
21
+ func cleanStr (str string ) (string , string ) {
22
+ // 转化成为干净的数字字符串
23
+ res , signed := "" , ""
25
24
// 死抠细节, 变态的数据。。
26
25
for _ , v := range str {
27
- if (v == ' ' || v == '-' || v == '+' ) && (len (temp ) > 0 || signed != "" ) {
26
+ if (v == ' ' || v == '-' || v == '+' ) && (len (res ) > 0 || signed != "" ) {
28
27
break
29
28
}
30
29
switch v {
@@ -40,15 +39,11 @@ func myAtoi(str string) int {
40
39
if _ , ok := ascii [v ]; ! ok {
41
40
break
42
41
}
43
- temp += string (v )
44
- }
45
- // temp已经成为干净的数字字符串,只需按位转为int即可
46
- for k , v := range temp {
47
- res += int (float64 (ascii [v ]) * math .Pow (10.0 , float64 (len (temp )- k - 1 )))
48
- }
49
- if signed == "-" {
50
- res = - res
42
+ res += string (v )
51
43
}
44
+ return res , signed
45
+ }
46
+ func checkOverflow (res int , signed string ) int {
52
47
// 注意太大值溢出变为负数的问题
53
48
max , min := math .MaxInt32 , - (math .MaxInt32 + 1 )
54
49
if res > max {
@@ -64,9 +59,23 @@ func myAtoi(str string) int {
64
59
}
65
60
}
66
61
}
67
-
68
62
return res
69
63
}
64
+ func myAtoi (str string ) int {
65
+ // 4 ms, 2.3 MB
66
+ temp , signed := cleanStr (str )
67
+ res := 0
68
+ // 对于clean后的字符串, 只需按位转为int即可
69
+ for k , v := range temp {
70
+ res += int (float64 (ascii [v ]) * math .Pow (10.0 , float64 (len (temp )- k - 1 )))
71
+ }
72
+
73
+ if signed == "-" {
74
+ res = - res
75
+ }
76
+
77
+ return checkOverflow (res , signed )
78
+ }
70
79
71
80
func main () {
72
81
fmt .Println (myAtoi ("2147483648" ))
0 commit comments