首页 > 其他 > 详细

leetcode-easy-string- 8 String to Integer (atoi)

时间:2019-06-10 13:21:24      阅读:100      评论:0      收藏:0      [点我收藏+]

mycode  98.26%

易错点: while循环式,and判断的地方先判断下标会不会超出范围

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str = str.strip()
        if not str :
            return 0
        res , start = ‘‘ , 0
        if str[0] == - or str[0] == + :
            res = str[0]
            start = 1 
        if start >= len(str) or not str[start].isnumeric() :
            return 0
        while start < len(str) and str[start].isnumeric():
            res += str[start]
            start += 1
        res = int(res) 
        if res > 2147483647 :
            res = 2147483647 
        elif res <  -2147483648:
            res = -2147483648
        return res
        

 

参考

思路:哪些情况下可以直接返回0呢 1) 空 2)+-符号不是开头3) 遍历到的字符不是空格、+-、数字

 def myAtoi(self, S):
        """
        :type str: str
        :rtype: int
        """
        res = ‘‘
        
        S1 = S.strip() # need to know
        
        for s in S1:   
            if s == ‘‘: continue
            if res != ‘‘ and s in +-: break   
            if s in -+0123456789:  # need to know
                res += s
            else:
                break
           
        if res == ‘‘ or res == + or res== -: 
            return 0
        elif int(res) < -2**31: 
            return -2**31
        elif int(res) > (2**31)-1:
            return (2**31) -1
        else: 
            return int(res)

 

leetcode-easy-string- 8 String to Integer (atoi)

原文:https://www.cnblogs.com/rosyYY/p/10996637.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!