LeetCode 8. 字符串转换整数 (atoi) Python3,Go
原题链接
中等
作者:
lkm
,
2021-04-07 11:30:37
,
所有人可见
,
阅读 326
Python3
class Solution:
def myAtoi(self, s: str) -> int:
sign, idx = 1, 0
while idx < len(s) and s[idx] == ' ': idx += 1
if idx < len(s) and s[idx] == '+': idx += 1
elif idx < len(s) and s[idx] == '-': idx += 1; sign = -1
num = 0
while idx < len(s) and s[idx] >= '0' and s[idx] <= '9':
num = num * 10 + int(s[idx])
idx += 1
num *= sign
maxv = 1 << 31
if num > 0 and num > maxv - 1: num = maxv - 1
if num < 0 and num < -maxv: num = -maxv
return num
Go
const maxv int64 = 1 << 31
func myAtoi(s string) int {
// go 中 int,系统多少位就多少位
var (
i int
sign int = 1
num int64
)
for i = 0; i < len(s); i++ {
if s[i] != ' ' {
break
}
}
if i < len(s) && s[i] == '-' {
sign = -1
i++
fmt.Println("have - ")
} else if i < len(s) && s[i] == '+' {
i++
}
for ; i < len(s) && s[i] >= '0' && s[i] <= '9'; i++ {
num = num * 10 + int64(s[i] - '0')
if num > maxv {
num = maxv
}
}
num *= int64(sign)
if num > maxv - 1 {
num = maxv - 1
}
if num < -maxv {
num = -maxv
}
return int(num)
}