Any suggestion on improving my accepted python code


  • 0
    L
    class Solution:
    # @return an integer
    def atoi(self, str):
        val=0
        flagNeg=0
        flagPos=0
        for i in range(len(str)):
            if str[i]==' ':
                if flagNeg==0 and flagPos==0 and val==0:
                    continue
                else:
                    break
            elif str[i]=='-':
                flagNeg=flagNeg+1
            elif str[i]=='+':
                flagPos=flagPos+1
            else:
                try:
                    key=int(str[i]) 
                    val=val*10+key
                except ValueError:
                    break
        if flagPos+flagNeg>1:
            val= 0
        else: 
            if flagNeg==1:
                if val>2147483647:
                    val=-2147483648
                else:
                    val=-val
            elif val> 2147483647:
                val = 2147483647
        return val
    

    My code looks awful. Any tips on improvement would be appreciated.

    I use a loop to scan trough every element in that string. Here firstly I would skip those ' '. Then I use two flag to record negative or positive signs respectively. Later if the sum of them is larger than one, which means there are multiple positive or negative signs, the output would become zero. Then I tried to convert that character into a number, if fails stop the convention.

    Once finishing the scanning, 1st check if the value if negative by examining the value of the flag. Then I check whether the value is large than the maximum value or smaller than the minimum value respectively.

    Thank you again for your attention.


Log in to reply
 

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