String to Integer (atoi) medium
Problem Statement
Implement the myAtoi(str)
function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi
function).
The algorithm for myAtoi
is as follows:
- Read in and ignore any leading whitespace.
- Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive.
- Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
- Convert these digits into an integer.
- If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
- Return the integer as the result.
Note:
- Only the space character ' ' is considered as whitespace character.
- Assume we are dealing with an environment which could only hold 32-bit signed integers. When the numerical value of the integer is out of the range of a 32-bit signed integer, return 231 - 1 if it is positive, and -231 if it is negative.
Example 1
Input: str = "42"
Output: 42
Explanation: The underlined characters are what is read in, and the result is 42.
Example 2
Input: str = " -42"
Output: -42
Explanation: The underlined characters are what is read in, and the result is -42.
Steps and Explanation
-
Whitespace Removal: The code first iterates through the input string to skip any leading whitespace characters.
-
Sign Determination: It then checks for an optional '+' or '-' sign. The sign is stored to determine the final sign of the integer.
-
Digit Extraction: The code iterates through the remaining characters, extracting digits until a non-digit character is encountered or the end of the string is reached.
-
Integer Conversion: The extracted digits are converted to an integer using a running total. We multiply the current total by 10 and add the next digit. This is efficient and avoids string concatenation.
-
Clamp to 32-bit Range: The resulting integer is checked against the limits of a 32-bit signed integer (-231 to 231 - 1). If it's outside this range, it's clamped to the appropriate boundary.
Code
def myAtoi(str):
"""
Converts a string to a 32-bit signed integer.
"""
str = str.strip() # Remove leading/trailing whitespace
if not str:
return 0
sign = -1 if str[0] == '-' else 1
if str[0] in ['-', '+']:
str = str[1:]
result = 0
for char in str:
if not char.isdigit():
break
result = result * 10 + int(char)
result *= sign
INT_MAX = 2**31 - 1
INT_MIN = -2**31
return max(min(result, INT_MAX), INT_MIN)
Complexity
- Time Complexity: O(n), where n is the length of the input string. We iterate through the string at most once.
- Space Complexity: O(1). The algorithm uses a constant amount of extra space.