1. Problem Statement (Simple Explanation):
You need to implement:
int myAtoi(string s)
which converts a string s to a 32-bit signed integer, following these rules:
Whitespace:
Ignore leading spaces " " until you hit the first non-space character.Sign:
If the next character is '-' or '+':'-' → number is negative
'+' → number is positive
If neither, assume positive.Conversion:
Read digits ('0'–'9') one by one:Skip any leading zeros (i.e., they don’t affect the value).
Stop when you encounter a non-digit or end of string.
If no digits are read at all → return 0.
Rounding (Clamping):
If the number goes outside the 32-bit signed range:
then:
If result < -231 → return -231
If result > 231-1 → return 231-1
Return the final integer.
2. Examples:
Example 1:
Input: s = "42"
Output: 42
Steps:
No leading whitespace.
No sign → positive.
Read "42" → 42.
Example 2:
Input: s = "-042"
Output: -42
Steps:
Skip " ".
See '-' → negative.
Read digits "042" → numeric value 42.
Apply sign → -42.
Example 3:
Input: s = "1337c0d3"
Output: 1337
Steps:
No leading whitespace.
No sign → positive.
Read "1337", stop at 'c' (first non-digit).
Result 1337.
Example 4:
Input: s = "0-1"
Output: 0
Steps:
No leading whitespace.
No sign.
Read "0", stop at '-' (non-digit).
Result 0.
Example 5:
Input: s = "words and 987"
Output: 0
Steps:
First char 'w' is not space, sign, or digit.
No digits read → return 0.
3. Basic Approach – Step-by-Step Parsing (Single Pass):
We parse the string once, left to right.
Algorithm (Step-by-Step):
Start by setting an index i to 0.
Also store the length of the string n, set the default sign to positive (1), and set result to 0.Ignore all leading spaces in the string.
Move i forward until you reach a non-space character or the end of the string.Check if the current character is a sign symbol:
If it is '+', keep the sign positive.
If it is '-', change the sign to negative.
Move the index forward if a sign was found.
Now begin reading characters as long as they are digits:
Convert the digit character into its numeric value.
Before adding it to result, check if adding this digit would cause an overflow:
If result is already larger than INT_MAX / 10, the next multiplication will overflow.
If result equals INT_MAX / 10 and the next digit is greater than 7, it will overflow.
If an overflow is detected:
Return INT_MAX if the sign is positive.
Return INT_MIN if the sign is negative.
If safe, update the number: multiply result by 10 and add the digit.
Move to the next character.
If no digit at all was processed, simply return 0.
Finally, multiply the result by the sign (positive or negative) and return the final number.
Pseudo-code (myAtoi):
Complexity:
Let n be the length of s:
Time: O(n)
One pass over the string.
Space: O(1)
Only a few variables.
4. Java code:
5. C code:
6. C++ code:
7. Python code:
Python’s ints are unbounded, but we simulate 32-bit behavior with clamping.
8. JavaScript:






Comments
Post a Comment