Leetcode Golang 8. String to Integer (atoi).go

2019-04-12 11:14:00 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412888

思路

先处理符号

注意越界问题

code

代码语言:javascript复制
func myAtoi(str string) int {
	pos := 1
	res := 0
	str = strings.TrimSpace(str)
	if len(str) == 0 {
		return res
	}
	i := 0
	if str[i] == ' ' {
		i  
		pos = 1
	} else if str[i] == '-' {
		i  
		pos = -1
	}
	for ; i < len(str); i   {
		if pos*res >= math.MaxInt32 {
			return math.MaxInt32
		}
		if pos*res <= math.MinInt32 {
			return math.MinInt32
		}
		if str[i] < '0' || string(str[i]) > "9" {
			return res * pos
		}
		res = res*10   int(str[i]) - '0'
	}
	if pos*res >= math.MaxInt32 {
		return math.MaxInt32
	}
	if pos*res <= math.MinInt32 {
		return math.MinInt32
	}
	return pos * res
}

0 人点赞