My AC Python solution, 130ms


  • 0
    B
    class Solution:
    # @return an integer
    def atoi(self, str):
        str = str.strip()
        if len(str) == 0: return 0
        r, i, l, s = 0, 0, 0, ''  
        if str[0] in '+-':  
            s = str[0]
            i = 1
        for i in xrange(i, len(str)):
            if '0' <= str[i] <= '9':
                r = r*10 + ord(str[i]) - ord('0')
                l += 1
            else:
                break
        if r == 0 and (s or l == 0):
            return 0
        elif r > 0 and s == '-':
            r *= -1
        if r > 2147483647:
            r = 2147483647
        if r < -2147483648:
            r = -2147483648
        return r
    

    r - result; i and s - index and content of the char after potential '+'/'-'; l - track if there's number;

    Not sure if string.strip() is not allowed. If it's not, it's also easy to remove white spaces in front of 1st char.


  • 0
    B

    smart. we end up the same technique..


Log in to reply
 

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