Friday, August 14, 2015

Leetcode 8. String to Integer (atoi)

https://leetcode.com/problems/string-to-integer-atoi/

The description may seem obscure, but actually it wants the first possible valid number in a string.

The detail requirement is a little weird. Note that once a possible number occurs, the problem wants it or you should return a zero if it in fact is not a number. For example, for '+-2' you should return 0 instead of -2, for '   b111' you should return 0 instead of 111. 

There are 4 cases:
1. Empty string or no valid number, return 0;
2. Number starts with '+';
3. Number starts with '-';
4. Number without any sign.

Solution:
# T:O(n) S:O(1)
class Solution:
    # @param {string} s
    # @return {integer}
    def myAtoi(self, s):
        INT_MAX, INT_MIN = 2147483647, -2147483648
        s = s.lstrip()
        if not s:
            return 0
        ret, sign, i = '', 1, 0
        if s[i] == '+':
            i += 1
        elif s[i] == '-':
            i += 1
            sign = -1
        elif '0' <= s[i] <= '9':
            ret += s[i]
            i += 1
        else:
            return 0
        while i < len(s) and '0' <= s[i] <= '9':
            ret += s[i]
            i += 1
        if not ret:
            return 0
        if sign * int(ret) > INT_MAX:
            return INT_MAX
        elif sign * int(ret) < INT_MIN:
            return INT_MIN
        else:
            return sign * int(ret) 
Run Time: 88 ms

No comments:

Post a Comment