美文网首页
String to Integer (atoi) 字符到数字

String to Integer (atoi) 字符到数字

作者: 穿越那片海 | 来源:发表于2017-06-17 20:00 被阅读0次

Medium, Array/String

将一个字符转换为数字,开头和结尾的空格忽略。开头的‘+’和‘-’需要考虑。

Solution

此题的关键是防止溢出,最大数为2^31-1,最小数为-2^31

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if len(str) == 0 : return 0
        ls = list(str.strip())
        
        sign = -1 if ls[0] == '-' else 1
        if ls[0] in ['-','+'] : del ls[0]
        ret, i = 0, 0
        while i < len(ls) and ls[i].isdigit() :
            ret = ret*10 + ord(ls[i]) - ord('0')
            i += 1
        return max(-2**31, min(sign * ret,2**31-1))

相关文章

网友评论

      本文标题:String to Integer (atoi) 字符到数字

      本文链接:https://www.haomeiwen.com/subject/evsbqxtx.html