String to Integer (atoi) — LeetCode 8 Python Solution
- Problem
- #8
- Pattern
- Hash Map
- Reading time
- 5 min
- Source
- leetcode.com
The problem
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 (" ").
Example
The underlined characters are what is read in and the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
^Python solution
class Solution:
def myAtoi(self, s: str) -> int:
if not s:
return 0
n = len(s)
if n == 0:
return 0
i = 0
while s[i] == ' ':
i += 1
if i == n:
return 0
sign = -1 if s[i] == '-' else 1
if s[i] in ['-', '+']:
i += 1
res, flag = 0, (2**31 - 1) // 10
while i < n:
if not s[i].isdigit():
break
c = int(s[i])
if res > flag or (res == flag and c > 7):
return 2**31 - 1 if sign > 0 else -(2**31)
res = res * 10 + c
i += 1
return sign * resComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(1) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 8. String to Integer (atoi) is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
On a study list
This problem is on Grind 75.
Frequently asked questions
- How hard is LeetCode 8. String to Integer (atoi)?
- LeetCode 8. String to Integer (atoi) is rated Medium on LeetCode.
- What is the time complexity of LeetCode 8. String to Integer (atoi)?
- The Python solution on this page runs in O(n), where n is the length of the string.
- What is the space complexity of LeetCode 8. String to Integer (atoi)?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 8. String to Integer (atoi) cover?
- LeetCode 8. String to Integer (atoi) is tagged String on LeetCode.