meishaoming / blog

MIT License
1 stars 2 forks source link

leetcode - 0008 字符串转换整数 (atoi) #74

Open meishaoming opened 4 years ago

meishaoming commented 4 years ago

https://leetcode-cn.com/problems/string-to-integer-atoi/

解法一

捏着鼻子先写下第一版解答

思路很简单:

  1. 先 strip 掉两边的空白字符
  2. 第一个字符要么是符号 '-' 或 '+', 要么是数字 0~9 ,确定好 start(如果不是那就不符合规则、返回 0)
  3. 接着来取数字,移动下标,找第一个非数字,就是 end
  4. 取出 s[start:end],转成 int 型
class Solution:
    def myAtoi(self, str: str) -> int:

        def isdigit(c):
            return c >= '0' and c <= '9'

        def isspace(c):
            return c == ' '

        s = str.strip()
        if len(s) == 0:
            return 0

        start = end = 0
        i = 0
        if s[0] == '-' or s[0] == '+':
            start = end = 1
            i = 1
        elif not isdigit(s[0]):
            return 0

        while i < len(s):
            if not isdigit(s[i]):
                end = i
                break
            else:
                i += 1
        else:
            end = i

        if start == end:
            return 0

        nums = int(s[start:end])
        if s[0] == '-':
            nums = -nums

        if nums < -0x80000000:
            nums = -0x80000000
        elif nums > 0x7fffffff:
            nums = 0x7fffffff

        return nums
image