LeetCode小随笔

问题:写一个函数 StrToInt,实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。

假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231,  231 − 1]。如果数值超过这个范围,请返回  INT_MAX (231 − 1) 或 INT_MIN (−231) 。

code:

class Solution:
    def strToInt(self, s: str) -> int:
        s = s.lstrip()
        if not s:
            return 0
        f = False
        if s[0] == '-' : 
            f = True
            s = s[1:]
        res = 0
        for char in s:
            if not char.isdigit():
                break
            res = res*10 + ord(char) - ord('0')
            # i += 1
        max_i, min_i = (1 << 32) - 1, -(1 << 32)
        if f : res = -res
        return max(min_i, min(max_i, res)) 

  

原文地址:https://www.cnblogs.com/lvpengbo/p/12570873.html