NOTE
把字符串转换成整数
记录字符串转整数的字符解析和 atoi 实现。
这是历史学习笔记,可能存在过时或不完整的理解。
1. 题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
2. 思路
- 转换成字符数组,
字符-'0'->数字
3. 实现
//时间复杂度:O(N)
//空间复杂度:O(1)
func StrToInt(str string) int {
if len(str) == 0 {
return 0
}
chars := []rune(str)
data := 0
opt := 1
for i := 0; i < len(chars); i++ {
ch := chars[i]
if ch >= '0' && ch <= '9' {
r := ch - '0'
data = data*10 + int(r)
} else if ch == '-' && i == 0 {
opt = -1
} else if ch == '+' && i == 0 {
opt = 1
} else {
return 0
}
}
return opt * data
}
func myAtoi(s string) int {
i := 0
n := len(s)
for i < n && s[i] == ' '{
i++
}
opt := 1
if i < n {
if s[i] == '+' {
opt = 1
i++
}else if s[i] == '-' {
opt = -1
i++
}
}
res := 0
for i < n && s[i] >= '0' && s[i] <= '9' {
res = res * 10 +int(s[i]-'0')
if opt*res < math.MinInt32 {
return math.MinInt32
}else if opt*res > math.MaxInt32 {
return math.MaxInt32
}
i++
}
return opt*res
}
讨论
使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看