# 题目链接
# 题目描述
将一个字符串转换成一个整数,字符串不是一个合法的数值则返回 0,要求不能使用字符串转换整数的库函数。
Iuput:
+2147483647
1a33
Output:
2147483647
0
1
2
3
4
5
6
7
2
3
4
5
6
7
# 解题思路
func strToInt(str string) int {
str = strings.TrimSpace(str)
result := 0
sign := 1
for i, v := range str {
if v >= '0' && v <= '9' {
result = result*10 + int(v-'0')
} else if v == '-' && i == 0 {
sign = -1
} else if v == '+' && i == 0 {
sign = 1
} else {
break
}
if result > math.MaxInt32 {
if sign == -1 {
return math.MinInt32
}
return math.MaxInt32
}
}
return sign * result
}
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
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