Simple Python Solution


  • 0
    H
    class Solution(object):
        def checkNumber(self, char):
            c = ord(char)
            if  c >= 48 and c <= 57:
                return True
            return False
    
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            if len(str) == 0:
                return 0
            res = 0
            sign = 1
            start = 0
            str = str.strip()
            if (str.startswith('-')):
                sign = -1
                start += 1
            if (str.startswith('+')):
                sign = +1
                start += 1
    
            for i in xrange(start, len(str)):
                if (self.checkNumber(str[i])):
                    res = res*10 + ord(str[i])-ord('0')
                else:
                    break
    
            number = sign*res
    
            if number > 2147483647:
                number = 2147483647
            if number < -2147483648:
                number = -2147483648
    
            return number
    

Log in to reply
 

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