Python3 Solution for ATOI


  • 0
    B

    The solution can be divided into the following steps:
    1.determine whether the input string is None, if it is. returned 0
    2.Remove the whitespace characters at both ends of the string, and save the processed characters
    3.determine whether the processed character length> 0,if equal to 0 ,then returns 0
    4.check if the first character is '+', '-' or >='0' and <='9'. If not, return 0
    5.Next traverse the string from the second character, if the current character is a number, save to str_number, otherwise terminating traversal
    6.Here we need to pay attention to several situations.
    (1) What type of data should be stored in the current string, it may not be completely stored in an INT or LONG
    (2)Can the “0012” data be converted from a string to an integer when converting?
    (3)When the number is greater than INT_MAX, the return value is INT_MAX, less than INT_MIN, the return value is INT_MIN, otherwise it returns the real number

    Here is My Code,Thanks for your reading!

    class Solution:
        def myAtoi(self, str1):
            if str1 is None:
                return 0
            str1 = str1.strip()
            if len(str1) == 0:
                return 0
    
            str_number = ""
            if str1[0] == '+' or str1[0] == '-' or (str1[0] >= '0' and str1[0] <= '9'):
                str_number += str1[0]
                for i in range(1, len(str1)):
                    if str1[i] >= '0' and str1[i] <= '9':
                        str_number += str1[i]
                    else:
                        break
                try:
                    num = int(str_number)
                    INT_MAX, INT_MIN = 2147483647, -2147483648
                    if num > INT_MAX:
                        return INT_MAX
                    elif num < INT_MIN:
                        return INT_MIN
                    else:
                        return num
                except:
                    return 0
            else:
                return 0
    

Log in to reply
 

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