[LeetCode][python3]0008. String to Integer (atoi)

Start the Journey
N2I -2020.03.15

1. My first solution


class Solution:
    def myAtoi(self, str: str) -> int:
        str2=''
        if not str:
            return 0
        for index,i in enumerate(str):
            if i in ['1','2','3','4','5','6','7','8','9','0']:
                break
            elif i!=' ':
                break
        if i=='+':
            index+=1
        if i=='-':
            str2+=i
            index+=1
        for i in range(index,len(str)):
            if str[i] in ['1','2','3','4','5','6','7','8','9','0']:
                str2+=str[i]
            else:
                break
                
        if not str2 or str2=="-":
            return 0
        x=int(str2)
        if x > 2147483648-1:
            return 2147483648-1
        elif x<-2147483648:
            return -2147483648
        
        return x


Explanation:

Though this is an easy one, it is still bothering to deal with the exceptions.


2. Other Answer


class Solution:
    def myAtoi(self, str: str) -> int:
        num = ""
        for char in str:
            if num != "" and char in " +-":
                break
            if char in '1234567890-+': 
                num += char
            elif char != " ":
                break
                
        if num in "+-":
            return 0
        else:    
            return min(max(int(num),-2**31),2**31-1)


Explanation:

This solution is more clean, but a little slower.

Comments