Easy to Understand Python Solution


  • 0
    B
    1. If empty string, return 0
    2. Remove leading, trailing, and middle whitespace
    3. Check for sign
    4. Check for int chars
    5. Try to convert resulting string of chars into an int
        num = 0
        INT_MAX = 2147483647
        INT_MIN = -2147483648
        signs = ['+', '-']
        chars = []
    
        if len(str) == 0:
            return num
    
        str = str.strip().split()[0]
    
        i = 0
        if str[i] in signs:
            chars.append(str[0])
            i += 1
    
        if i < len(str):
            while str[i] in ['1','2','3','4','5','6','7','8','9','0']:
                chars.append(str[i])
                i += 1
                if i == len(str):
                    break
    
        try:
            num = int(''.join(chars))
            return max(min(num, INT_MAX), INT_MIN)
        except:
            return num
    

Log in to reply
 

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