Lever's Castle

8. 字符串转换整数 (atoi)

November 24, 2019

https://leetcode-cn.com/problems/string-to-integer-atoi/

使用语言:Go

func myAtoi(str string) int {
    MIN := -2147483648
    MAX := 2147483647
    isNegative := false
    hasNum := false
    var res int
    for _, c := range str {
        if res == 0 && !hasNum {
            // 32 - space,0 - 空字符,10 - 换行
            if c == 32 || c == 0 || c == 10 {
                continue
            }
            // 43 +,45 -
            if c == 45 {
                isNegative = true
                hasNum = true
                continue
            } else if c == 43 {
                hasNum = true
                continue
            }
        }
        // 0~9 - 48~57
        if c < 48 || c > 57 {
            break
        }
        if isNegative {
            if -res < (MIN + int(c) - 48) / 10 {
                return MIN
            }
        } else if res > (MAX - int(c) + 48) / 10 {
            return MAX
        }
        res = res * 10 + int(c) - 48
        hasNum = true
    }


    if isNegative {
        res = -res
    }


    return res
}

题目比较简单,按照题目过滤掉不符合条件的字符就可以了,这里复习了一下各种字符的 ASCII 表示。跟 7.正数反转 一样需要注意整数边界。另外这里发现了之前的处理中在做边界判断的时候有个问题,不应该用结果去判断是否超过 max 或 min,而应该用 max 或 min 缩减相应的值去跟结果判断大小。因为当结果做完运算之后,可能已经溢出了。还需要注意的是,在 Go 中,遍历字符串拿到的每个元素实际上是 rune 类型,在这里,我们需要把他转成 int 才能正常使用。


Lever

痕迹
没有过去,就没法认定现在的自己