8. String to Integer (atoi) - cocoder39/coco39_LC GitHub Wiki

8. String to Integer (atoi)

class Solution:
    def myAtoi(self, s: str) -> int:
        num = []
        canHaveSign = True
        canHaveSpce = True
        sign = 1
        num = 0
        for ch in s:
            if ch == ' ':
                if not canHaveSpce:
                    break
            elif ch in '+-':
                if not canHaveSign:
                    break
                canHaveSign = False
                canHaveSpce = False
                sign = 1 if ch == '+' else -1
            elif ch.isdigit():
                canHaveSign = False
                canHaveSpce = False
                num = 10 * num + int(ch)
            else:
                break
        
        if sign == -1 and num > 2**31:
            return -2**31
        if sign == 1 and num > 2**31 - 1:
            return 2**31 - 1
        return sign * n
class Solution:
    def myAtoi(self, s: str) -> int:
        index = 0
        n = len(s)
        while index < n and s[index] == ' ':
            index += 1
        
        sign = 1
        if index < n and s[index] in '+-':
            if s[index] == '-':
                sign = -1
            index += 1
        
        res = 0
        postive_max = 2**31 - 1
        negative_max = 2**31
        while index < n and '0' <= s[index] <= '9':
            res = ord(s[index]) - ord('0') + res * 10
            index += 1
            if sign == 1 and res >= postive_max:
                return postive_max
            elif sign == -1 and res >= negative_max:
                return -negative_max
        return sign * res