8. String to Integer (atoi)
url: https://leetcode.com/problems/string-to-integer-atoi/description/
Example
Input: s = “1337c0d3”
Output: 1337
Explanation:
Step 1: “1337c0d3” (no characters read because there is no leading whitespace)
Step 2: “1337c0d3” (no characters read because there is neither a ‘-‘ nor ‘+’)
Step 3: “1337c0d3” (“1337” is read in; reading stops because the next character is a non-digit)
💻 Code
Approach :
- Ignore every comming string elements.
- Make sure set the Max & Min range.
- check sign first, and integers.
- TC :
O(n) - SC:
O(1)
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
28
29
30
31
32
33
34
35
class Solution:
def myAtoi(self, s: str) -> int:
max_int = 2**31 - 1
min_int = -2**31
i = 0 # current index
n = len(s)
# Step 1: Whitespace exists, then move current index
while i < n and s[i] == ' ':
i += 1
# Step 2: recognizing positive (1) or negative (-1)
# Check the very first sign only!
sign = 1
if i < n and (s[i] == '+' or s[i] == '-'):
if s[i] == '-':
sign = -1
i += 1
# Step 3: now we check integers only
result = 0
while i < n and s[i].isdigit():
result = result * 10 + int(s[i]) # convert str -> int
i += 1
result *= sign
# checking the range validation
if result < min_int:
return min_int
if result > max_int:
return max_int
return result
This post is licensed under CC BY 4.0 by the author.