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 (
" "
). - Signedness: Determine the sign by checking if the next character is
'-'
or'+'
, assuming positivity is neither present. - Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
- Rounding: If the integer is out of the 32-bit signed integer range
[-2^31, 2^31 - 1]
, then round the integer to remain in the range. Specifically, integers less than-2^31
should be rounded to-2^31
, and integers greater than2^31 - 1
should be rounded to2^31 - 1
.
Return the integer as the final result.
Examples
Example 1:
|
|
Some Important Points and Questions Before Coding
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Q1. Does string contain whitespace characters before the number? A. Yes Q2. Can the string have garbage characters after the number? A. Yes. Ignore it. Q3. If no numeric character is found before encountering garbage characters, what should I do? A. Return 0. Q4. What if the integer overflows? A. Return INT_MAX if the number is positive, INT_MIN otherwise. Warning : DO NOT USE LIBRARY FUNCTION FOR ATOI. If you do, we will disqualify your submission retroactively and give you penalty points.
Solution
The following cases should be considered for this problem:
|
|
Method 1 - String Iteration
Here are the steps we can follow:
- Step 1: The string is trimmed to remove any leading whitespace.
- Step 2: If there is a sign character (
'-'
or'+'
), the sign is recorded, and the index is incremented. - Step 3: The characters are converted to integers until a non-digit character is encountered or the end of the string is reached.
- Step 4: During conversion, the algorithm checks for overflow and adjusts the result to stay within the 32-bit signed integer limits, returning
Integer.MAX_VALUE
orInteger.MIN_VALUE
if necessary. Finally, the sign is applied to the result.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the length of the string. - 🧺 Space complexity:
O(1)