JZ49 把字符串转换成整数

把字符串转换成整数

题目:将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0.

思路:这道题其实没有想象的那么多的边界条件,也没有那么繁琐。首先理解题目意思,是字符串转换为整数,不是小数,没有小数点或科学计数法的考量。

然后一个字符转换为整数的方法是,res = res * 10 + str[i] - '0';

边界情况

1)开始都是空格

2)考量第一个出现的字符是+,-

3)转换的数字大于INT_MAX,小于INT_MIN。

4)出现其他非数字字符。

使用一个全局变量记录是否是输入错误,因为return 0有很多种情况,也可能是字符串就一个0,返回也是0,因此需要设置一个变量区分开来。

 

func StrToInt(str string) int {
    res := 0
    flag := 1
    start := 0
    // space
    for start <= len(str)-1 && str[start] == ' ' {
        start++
    }
    // +/-
    if start <= len(str)-1 {
        if str[start] == '-' {
            flag = -1
            start++
        } else if str[start] == '+' {
            start++
        }
    }
    // is digital ?
    for start <= len(str)-1  {
        if !isDigital(str[start]) {
            return 0
        }
        if res == 0 {
            res += int(str[start] - '0')
            start++
        } else {
            res = res*10 + int((str[start] - '0'))
            start++
        }
        // overflow int32
        if res*flag > math.MaxInt32 {
            return math.MaxInt32
        } else if res*flag < math.MinInt32 {
            return math.MinInt32
        }
    }

    res *= flag
    return res
}

func isDigital(b byte) bool {
    if b <= '9' && b >= '0' {
        return true
    }
    return false
}

 

posted @ 2021-04-10 20:41  zqlucky  阅读(57)  评论(0编辑  收藏  举报