Problem Description
Implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s)
follows specific steps to handle whitespace, signedness, and conversion while ensuring the result stays within the 32-bit signed integer range.
Key Insights
- Ignore leading whitespace.
- Determine the sign based on the presence of '+' or '-'.
- Skip leading zeros when converting to integer.
- Handle overflow and underflow by clamping the result to the range of [-2^31, 2^31 - 1].
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), as we are using a constant amount of space.
Solution
The solution involves:
- Traversing the string to ignore leading whitespace.
- Checking for a sign indicator ('+' or '-') and adjusting a sign variable accordingly.
- Iterating through the characters to read digits while skipping leading zeros.
- Converting the digits into an integer and checking for overflow conditions to ensure the result is within the 32-bit signed integer range.