Skip to main content

8. String to Integer (atoi)

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

Python

Test cases are really special

  • "42"
  • "-41"
  • "00000-42a1234"
  • " +0 123"
  • "words and 987"
  • "-"
  • "-5-"
  • "-+12"
class Solution:
def myAtoi(self, s: str) -> int:
chars = s.strip()
num_chars = []

if not chars:
return 0

seem_num = False
seem_sign = False

for i in range(len(chars)):
char = chars[i]

if not char.isnumeric():
if seem_num:
break
elif char == '+':
if seem_sign:
return 0
seem_sign = True
elif char == '-':
if seem_sign:
return 0
seem_sign = True
num_chars.append('-')
else:
break
else:
num_chars.append(char)
seem_num = True

if not num_chars or (len(num_chars) == 1 and num_chars[0] == '-'):
return 0

number = int(''.join(num_chars))
limit = 2**31

if number > limit-1:
return limit-1
if number < -limit:
return -limit
return number