Write myAtoi(s), which reads a whole number from the start of the string s and returns it as a 32-bit signed integer. Do it by hand: no built-in that turns text into a number.
Read in this order. Skip any spaces at the start. Then an optional single + or - sets the sign. Then read digits until a character that is not a digit, or the end; leading zeros are fine. If no digits were read, the answer is 0.
If the number is outside the 32-bit range, clamp it: anything above 2,147,483,647 becomes 2,147,483,647, and anything below −2,147,483,648 becomes −2,147,483,648.
Example 1
Input: s = " -0307z" Output: -307 Why: skip the space, read the sign, then digits up to z
2 more examples and the constraints
Example 2
Input: s = "word 52" Output: 0 Why: the first character is a letter, so no digits
Example 3
Input: s = "-80000000000" Output: -2147483648 Why: too small for 32 bits, so it is clamped
Constraints
- 0 ≤ length of s ≤ 200
- s contains English letters, digits, spaces,
+,-and.
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Parse with a 64-bit totalO(n)
- Parse with an overflow guardO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 200 characters | Verdict |
|---|---|---|---|
| Parse with a 64-bit total | O(n) | Passes; needs a wider type | |
| Parse with an overflow guard | O(n) | Best; 32-bit math only |
n = the length of s.
Edge cases to test
- Empty or all spaces. "" and " " read no digits, so the answer is 0.
- A sign with no digits. "-" and "+-12" give 0: after one sign the next character must be a digit.
- Exactly at the limits. "2147483647" and "-2147483648" come back unchanged; one more in size is clamped.
- Very long digit runs. 200 nines would overflow even 64 bits, so the code must stop or clamp early.
- Leading zeros. "0000…012345678" is 12,345,678; zeros at the front add nothing.
Common mistakes
- Checking for overflow after
result * 10 + d, when the value has already wrapped around. - Skipping spaces between the sign and the digits, or anywhere after the start.
- Accepting a second sign, so "+-12" becomes −12 instead of 0.
How to talk through it
- 1Clarify. Which characters count as spaces? Can there be two signs? What happens on overflow?
- 2Name the phases. Spaces, then one sign, then digits, then stop at the first non-digit.
- 3Explain the guard. Check
result > (INT_MAX − d) / 10before multiplying, so nothing ever overflows. - 4Code it in one pass. One index moves left to right through all three phases.
- 5Test out loud. Run "", "-", "+-12", "2147483648" and "-2147483649".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?