7. 整数反转

方法一:

class Solution:
    def reverse(self, x: int) -> int:
        flag = 1 if x >= 0 else -1
        d = int(str(abs(x))[::-1]) * flag

        return d if 2**31 - 1 >= d >= -2**31 else 0

方法二:

class Solution:
    def reverse(self, x: int) -> int:
        res = 0
        flag = -1 if x < 0 else 1
        y = abs(x)
        while y:
            y, tem = divmod(y,10)
            res = res * 10 + tem
            if 2**31 - 1 < res or res * flag < -2**31:
                return 0
           
        return res * flag

8. 字符串转换整数 (atoi)

方法一:

class Solution:
    def myAtoi(self, s: str) -> int:
        s = s.strip()
        if s == '': return 0

        x, tem, flag = 0, '', -1 if s[0] == '-' else 1
        # 去掉符号位
        # if s[0] == '-' or s[0] == '+': s = s[1:]
        if s[0] in ['-','+']: s = s[1:]

        for c in s:
            if not c.isdigit(): break
            tem += c

        if tem:
            x = int(tem) * flag
            if x < -2**31: x = -2**31
            if x > 2**31 - 1: x = 2**31 - 1

        return x

方法二: re

class Solution:
    def myAtoi(self, s: str) -> int:
    	# *args 和 **kwargs 不定长参数,re.findall 结果是列表作为解包提供给 int
        return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)

方法三:

class Solution:
    def myAtoi(self, s: str) -> int:
        s = s.strip()
        if not s : return 0
        
        x, tem = 0, ''
        if s[0] in ['-','+']: 
            tem = s[0]
            s = s[1:]
        # 去除只有一个符号 '+' 或连续 '+-' 开头的串,如果第一个是符号,则第二个必须是数字。
        if not s or not s[0].isdigit(): return 0

        for c in s:
            if not c.isdigit(): break
            tem += c

        return max(min(int(tem),2**31 - 1),-2**31)