blog/source/_posts/2020-04-16-leetcode-string-to-integer-atoi.md
Ching 9690121403 feat(init project): add all existing files
add all existing files

Signed-off-by: Ching <loooching@gmail.com>
2022-02-02 19:04:18 +08:00

943 B

title date tags categories
leetcode-string-to-integer-atoi 2020-04-16 19:50:10 leetcode

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

题目

没什么好说的,注意各种情况,识别到数字之后就一直要是数字。

class Solution:
  def myAtoi(self, str: str) -> int:
    p = ''
    str = str.lstrip()
    n = ''
    min_int = -2**31
    max_int = 2**31-1
    isnumeric = False
    for x in str:
      if not isnumeric and x == '-':
        p = '-'
        isnumeric = True
        continue
      if not isnumeric and x == '+':
        isnumeric = True
        continue
      if x.isnumeric():
        n += x
        isnumeric = True
      else:
        break
    if not n:
      return 0
    if int(n) > max_int:
      if p:
        return min_int
      else:
        return max_int
    p += n
    return int(p)
# 32 ms	13.6 MB