The problem “String to Integer (atoi)” as described on LeetCode is as follows:
Implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi
function).
The algorithm for myAtoi(string s)
is as follows:
'-'
or '+'
. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present."123" -> 123
, "0032" -> 32
). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).Example 1:
Input: "42"
Output: 42
Example 2:
Input: " -42"
Output: -42
Example 3:
Input: "4193 with words"
Output: 4193
def myAtoi(s: str) -> int:
# Constants for integer limits
INT_MIN, INT_MAX = -2**31, 2**31 - 1
# Step 1: Ignore leading whitespace
s = s.lstrip()
if not s:
return 0
# Step 2: Check for the sign
sign = 1
start_index = 0
if s[start_index] in ['-', '+']:
if s[start_index] == '-':
sign = -1
start_index += 1
# Step 3 and 4: Read digits and convert to integer
num = 0
for i in range(start_index, len(s)):
if not s[i].isdigit():
break
num = num * 10 + int(s[i])
# Apply the sign
num *= sign
# Step 5: Clamp the integer to be within the 32-bit signed integer range
if num < INT_MIN:
return INT_MIN
if num > INT_MAX:
return INT_MAX
return num
The time complexity for this solution is O(n), where n is the length of the input string s
. The operations of stripping whitespaces and converting digits are linear with respect to the input length.
The space complexity is O(1), as only a constant amount of extra space is used, regardless of the input size.
This solution efficiently handles the problem’s requirements and edge cases, providing a correct implementation of the atoi
function.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?