美文网首页
LeetCode 8. String to Integer (a

LeetCode 8. String to Integer (a

作者: 费城的二鹏 | 来源:发表于2018-11-21 10:50 被阅读8次

    String to Integer (atoi)

    class Solution:
    
        maxNum = pow(2, 31)
    
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            isStart = False
            isF = False
            result = 0
            for char in str:
                if not isStart:
                    if char == ' ':
                        continue
                elif char not in "0123456789":
                    if isF:
                        result = -result
                    print(result)
                    return result
                
                if char in "+-0123456789":
                    isStart = True
                    if char == '-':
                        isF = True
                        continue
                    elif char == '+':
                        continue
                    else:
                        result = result * 10 + int(char)
    
                        if isF:
                            if -result <= -self.maxNum:
                                result = -self.maxNum
                                print(result)
                                return result
                        else:
                            if result >= self.maxNum - 1:
                                result = self.maxNum - 1
                                print(result)
                                return result
                else:
                    if isF:
                        result = -result
                    print(result)
                    return result
    
            if isF:
                result = -result
            print(result)
            return result
    

    相关文章

      网友评论

          本文标题:LeetCode 8. String to Integer (a

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