4 - step Python Solution with detailed explanation


  • 0
    W

    This is a python implementation based on the most-voted solution. It can be split into 4 parts:

    1. Remove preceding zeros;
    2. Determine the sign;
    3. Handle overflow;
    4. Deal with invalid inputs.

    For step 1, we can use built-in function str.lstrip() to finish, but note that unlike trim() in JAVA. Cos str.lstrip() just creates another string instead of changing the original one. That's why we have str = str.lstrip();

    For step 2, straight-forward idea;

    For step 3, well, in Python 3 or above, there is no limit on Integer(we don't need care about this if the testcase is Python-specific); However, by convention, we still need to handle it. I guess the code tells everything.

    For step 4, the most-upvoted solution seems not to care about length of the 'stripped' str; In my code, every time you increment i, you need to check whether it is still in the range. In this way, invalid inputs are handled quite efficiently and smartly.

    Correct me when you find anything weird. Happy coding!

    class Solution(object):
        def myAtoi(self, str):
            i = 0; sign = 1; base = 0
            str = str.lstrip()
            length = len(str)
            MAX_INT = 2147483647
            MIN_INT = -2147483648
            if i < length and (str[i] == '+' or str[i] == '-'):
                sign = 1 - 2 * (str[i] == '-')
                i += 1
            while i < length and str[i] >= '0' and str[i] <= '9':
                if base > int(MAX_INT / 10) or (base == int(MAX_INT / 10) and ord(str[i]) - ord('0') > 7):
                    return MAX_INT if sign == 1 else MIN_INT
                base = base * 10 + int(str[i])
                i += 1
            return base * sign
    

Log in to reply
 

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