Python solution with detailed explanation


  • 0
    G

    Solution

    String to Integer (atoi) https://leetcode.com/problems/string-to-integer-atoi/

    Algorithm

    • This is an integer related question and we should be careful about negative integers and overflow and underflow.
    • Whitespaces must be stripped off. There can be a leading + or - symbol.
    • INT_MAX = 2**31-1.
    • INT_MIN = -2**31.
    • Notice again the trick: num * 10 + int(ch). Do this with an example like 112. num = 1. num = 1 * 10 + 1 = 11. num = 11 * 10 + 2 = 112.
    • str.isdigit() and str.strip().
    class Solution(object):
        def myAtoi(self, str):
            num, neg = 0, 1
            # Strip off leading and trailing whitespaces
            str = str.strip()
            INT_MIN, INT_MAX = -2**31, 2**31-1
            for i,ch in enumerate(str):
                if ch.isdigit():
                    num = num*10 + int(ch)
                    # Test for overflow and underflow
                    if num*neg > INT_MAX:
                        return INT_MAX
                    if num*neg < INT_MIN:
                        return INT_MIN
                # Ignore leading + sign
                elif (i==0 and ch == "+"):
                    pass
                # Use the leading "-" sign to determine number is negative
                elif (i==0 and ch == "-"):
                    neg = -1
                # The string can contain additional characters after those that
                # form the integral number, which are ignored and have no effect 
                # on the behavior of this function.
                else:
                    break
            return num*neg
    

Log in to reply
 

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