题目
解答
这题恶心。。。没意义
func myAtoi(s string) int {
trimedStr := strings.TrimLeft(s, " ")
if trimedStr == "" {
return 0
}
str := []rune(trimedStr)
//注意,这个字符可能不存在,这时候不需要去掉这个字符
isPositive := true
if str[0] == '-' {
isPositive = false
}
if !unicode.IsDigit(str[0]) {
str = str[1:]
}
i := 0
for i < len(str) {
if !unicode.IsDigit(str[i]) {
break
}
i++
}
//这个时候,i可能是超下标了,或者这时的i位置不是数字,所以取str[:i]而不是str[:i+1]
str = str[:i]
if len(str) == 0 {
return 0
}
result, _ := strconv.Atoi(string(str))
//这里别粗心,不是isPositive,才为负数
if !isPositive {
result = 0 - result
}
if result > math.MaxInt32 {
return math.MaxInt32
} else if result < math.MinInt32 {
return math.MinInt32
} else {
return result
}
}
知识点
1、去除字符串开头所有字符
是strings.TrimLeft(s, " "),不是strings.TrimPrefix(s, " ")
2、审题,还可能出现这种情况
3、审题,边界条件处理
4、题目有问题
????