My Soluton Python


  • 0
    V

    here is code

    class Solution:
        # @return an integer
        def atoi(self, str):
            string = str
            buf = ''
            # our list
            dg_list = ['0','1','2','3','4','5','6','7','8','9']
            dg_signal = ['-','+']
        
            signal = ''
            
            #there is no +/- and 0-9 at first
            no_signal = True
            no_dig = True
            #strip whitespace
            for i in string.strip():
                
                #if i in dg_signal judge:
                #1:it is the first -/+ and signal = -/+, then set no_signal = False . Start to next i
                #2:it it the second -/+ So it is wrong,we return 0
                if i in dg_signal:
                    if no_signal is False:
                        return 0
                    if no_signal:
                        signal += i
                        no_signal=False
                        continue
                #if i is 0-9, we save it to buf
                if i in dg_list:
                    buf+=i
                #but if there is a -/+, and the next char is not dig, eg:+a   here we break.     
                elif no_signal is False:
                    break
                else:
                    #if it is not in dg_list and dg_signal,and it is also has something eg:+322a99  when i = a  and buf = +322. We jsut break a and continue 
                    #add 99 to buf
                    if len(buf)>0:
                        break
                    #if len(buf)<0.  eg: -a. We return as the sys tips
                    if len(buf)<=0:
                        return 0
                
                
            #add +/-
            if len(buf)>0:
                buf=signal+buf
            
            if len(buf)<=0:
                return 0
            
            f_result = int(buf)
            
            if f_result >2147483647:
                return 2147483647
            if f_result<-2147483648:
                return -2147483648
                
            return f_result
    

    {}

    Finally find {} button....


Log in to reply
 

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