Python simple solution


  • 0
    S
    class Solution(object):
        def myAtoi(self, s):
            """
            :type s: str
            :rtype: int
            """
            s = s.strip()
            retstr = ''
            try:
                for _, item in enumerate(s):
                    if item == '+' or item == '-':
                        retstr += item
                    else:
                        # if item can not convert to int, will throws a exception, it can filter the char that is not a number
                        retstr += str(int(item))
            finally:
                if len(retstr) == 0:
                    return 0
                else:
                    # if s is '-' or '+',len(retstr != 0) but throws a exception,should return 0
                    try:
                        a = int(retstr)
                        # just for int32 value is limited -2147483648 to 2147483647,but python int is Unlimited
                        if a > 2147483647:
                            return 2147483647
                        elif a < -2147483648:
                            return -2147483648
                        else:
                            return a
                    except:
                        return 0
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.