Most Concise Python Solution(7 lines) I Can Come Up With


  • 0
    E
    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            valid = ''
            
            for char in str.strip():
                if (char in '+-' and len(valid) == 0) or char.isdigit():
                    valid += char
                else:
                    break
            return 0 if valid in '+-' else {int(valid) > 2147483647: 2147483647, int(valid) < -2147483648: -2147483648}.get(True, int(valid))
    

    Notes: Iterate through str to get '+' or '-' if any of them starts the string, and break as soon as non-digit is found, either at the very beginning or in the middle. Now valid will either be '+' or '-' or a valid integer. Sacrificed some readability in return line, and took advantage of those two keys in dict cannot be True at same time.

    P.S. Not a fan of this problem, and I would never expect -12a8473 to be converted as -12 in real life problems.


Log in to reply
 

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