StringToInteger
Problem
Solution
Track the value of the integer as in separate sign and value variables.
Use
s.strip()to remove any whitespace.Check if the string is empty. If so, return 0.
Check the first character of the string. If it is ‘+’ or ‘-’, the number portion of the string starts at 1. Set the
signbased on the character or default to a positive sign.Get all the numeric digits in the string.
From the end, increase
valueby \(\textrm{digit}_i * 10^i\). Ifvalueexceeds the int32 limits of \([-2^{32}, 2^{32} - 1]\), clampvalue.
Code
def myAtoi(s: str) -> int:
"""Convert string to integer.
"""
sign = 1
value = 0
s = s.strip()
if len(s) == 0:
return 0
sign_char = s[0]
num_start = 0
if sign_char in {'-', '+'}:
num_start = 1
if sign_char == '-':
sign = -1
num_string = ''
for char in s[num_start:]:
if not char.isnumeric():
break
num_string += char
for i, char in enumerate(reversed(num_string)):
value += int(char) * 10**i
if sign == 1 and value >= 2**31 - 1:
return 2**31 - 1
elif sign == -1 and value >= 2**31:
return -2**31
return sign * value
Test
>>> from StringToInteger import myAtoi
>>> myAtoi('42')
42
>>> myAtoi(' -42')
-42
>>> myAtoi('4193 with words')
4193
- StringToInteger.myAtoi(s: str) int
Convert string to integer.