Leetcode 8. String to Integer (atoi)

来源:互联网 发布:java界面编程在哪 编辑:程序博客网 时间:2024/06/10 02:28

题目:Implement atoi to convert a string to an integer.

思路:编写相应规则即可.


import ctypes
class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        intMax=2147483647
        intMin=-2147483648
        str = str.strip()
        s = '';f = True
        for i in str:
            if f and i=='-':f=False;s+=i;continue
            if f and i=='+':f=False;continue
            if '9'>=i>='0':
                s+=i
            else:break
        try:
            a = int(s)
            if a>intMax:return intMax
            if a<intMin:return intMin
            return a
        except:
            return 0

0 0