Description

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.

The algorithm for myAtoi(string s) is as follows:

  • Whitespace: Ignore any leading whitespace (“ “).
  • Signedness: Determine the sign by checking if the next character is ‘-‘ or ‘+’, assuming positivity if neither present.
  • Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
  • Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1.

Return the integer as the final result.

Example 1:

1
2
Input: "42"
Output: 42

Example 2:

1
2
3
4
Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which indicates an negative sign.
Then take the rest of the string after the sign. "42" is the integer part.

Example 3:

1
2
3
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a digit.

Example 4:

1
2
3
4
Input: "words and 987" 

Output: 0
Explanation: The first non-whitespace character is 'w', which indicates an invalid input.

Example 5:

1
2
3
4
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore, the integer overflows and becomes negative. The function should return -2147483648.

Constraints:

  • 0 <= s.length <= 200
  • s consists of English letters (lower-case and upper-case), digits (0-9), ‘ ‘, ‘+’, ‘-‘, and ‘.’.

Approach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
def myAtoi(self, s: str) -> int:
s = s.lstrip()
if not s:
return 0

sign = 1
if s[0] in ['-', '+']:
if s[0] == '-':
sign = -1
s = s[1:]

num = 0
for ch in s:
if not ch.isdigit():
break
num = num * 10 + int(ch)

num *= sign

INT_MIN, INT_MAX = -2**31, 2**31 - 1
if num < INT_MIN:
return INT_MIN
if num > INT_MAX:
return INT_MAX
return num