剑指 Offer 67. 把字符串转换成整数

题目:  中等

 

 方法:emmm  时间复杂度O(n)  空间复杂度O(n)  

没啥特殊的,就是代码细节挺多

def strToInt(str):
        """
        :type str: str
        :rtype: int
        """
        s = str.strip()    # 一定是先strip再判断,否则'     '这种后续会报错
        if s == '':
            return 0

        idx = 0
        sign = 1
        if s[idx] in '+-':
            if s[idx] == '-':  # 犯过错,一定后执行idx+1
                sign = -1
            idx += 1
            
        int_max = 2**31 - 1
        int_min = -2**31

        res = 0
        for i in range(idx,len(s)):
            if not '0' <= s[i] <= '9':
                break
            res = res * 10 + int(s[i])
            if res > int_max:  # 因为此时res是无符号的,所以判断放一起
                return int_max if sign == 1 else int_min
            
        return sign * res

 

posted @ 2022-08-06 16:36  Liang-ml  阅读(15)  评论(0)    收藏  举报