Skip to content

Latest commit

 

History

History
36 lines (32 loc) · 772 Bytes

67. 把字符串转换成整数.md

File metadata and controls

36 lines (32 loc) · 772 Bytes

解题思路

模拟

func strToInt(s string) int {
    s = strings.Trim(s, " ")
    minus := 1
    var ans int64 = 0
    for i := range s {
        // 处理正负号
        if i == 0 && (s[i] == '+' || s[i] == '-') {
            if s[i] == '-' {
                minus = -1
            }
            continue
        }
        // 非数字非 +/-,直接跳出
        if s[i] < '0' || s[i] > '9' {
            break
        }
        // 处理数字
        ans = ans * 10 + int64(s[i]-'0')
        if minus == 1 && ans > math.MaxInt32 {
            return math.MaxInt32
        } else if minus == -1 && ans > math.MaxInt32+1 {
            return math.MinInt32
        }
    }
    return int(ans) * minus
}