Browse curriculum

String to Integer (atoi)

Convert a string to a 32-bit signed integer the way C's atoi does: skip leading spaces, read an optional sign and digits, and clamp on overflow.

Problem Understanding

String to Integer (atoi) (LeetCode 8): implement myAtoi(s). Ignore leading spaces; read an optional + or -; read digits until a non-digit or the end of the string, ignoring leading zeros. If no digits were read, return 0. Clamp the result to the 32-bit range [-2^31, 2^31 - 1].

Examples: "42" → 42; " -042" → -42; "1337c0d3" → 1337; "0-1" → 0; "words and 987" → 0.

The Intuition: Rules in Order, One Index

atoi is a small state machine you can write as three loops in a row, all moving the same index.

  1. Spaces: skip them.
  2. Sign: at most one + or -.
  3. Digits: build the number left to right, result = result × 10 + digit, and stop at the first character that is not a digit.

The only subtle part is overflow. Check before you multiply, so the value never leaves the 32-bit range. The digit-by-digit building is the same as Add Strings, and the overflow guard is the one used in Reverse Integer.

Interactive Walkthrough

RULES IN ORDER

START AT 0

s

␣

0

␣

1

␣

2

-

3

0

4

4

5

2

6

result = 0

Sign

+

i

:

Digits

0

 

Start at i = 0. Result 0, sign +1. The limits are -2147483648 and 2147483647

Next

s[0] is a space: skip it

Free preview: the first 3 of 9 steps

s

Spaces are drawn as ␣ so you can see them being skipped. Try Example 4: the - after the 0 is not a sign, it just ends the number. Overflow stops one digit early and returns the limit.

Dry Run Table

Input: s = " -042".

i s[i] Rule sign result
0 to 2 space skip leading spaces +1 0
3 - read the sign -1 0
4 0 digit: 0 × 10 + 0 -1 0
5 4 digit: 0 × 10 + 4 -1 4
6 2 digit: 4 × 10 + 2 -1 42

The string ends. Answer: -1 × 42 = -42. The leading zero is simply absorbed.

The Solution Template

One index and three loops. The overflow check compares with INT_MAX / 10 before multiplying, so it is safe in fixed-width integers.

String to Integer (atoi) Code
1var myAtoi = function(s) {
2 const INT_MAX = 2 ** 31 - 1, INT_MIN = -(2 ** 31);
3 let i = 0;
4 const n = s.length;
5 while (i < n && s[i] === ' ') {
6 i++;
7 }
8 let sign = 1;
9 if (i < n && (s[i] === '+' || s[i] === '-')) {
10 sign = s[i] === '-' ? -1 : 1;
11 i++;
12 }
13 let result = 0;
14 while (i < n && s[i] >= '0' && s[i] <= '9') {
15 const digit = s.charCodeAt(i) - 48;
16 if (result > Math.floor(INT_MAX / 10) || (result === Math.floor(INT_MAX / 10) && digit > 7)) {
17 return sign === 1 ? INT_MAX : INT_MIN;
18 }
19 result = result * 10 + digit;
20 i++;
21 }
22 return sign * result;
23};

Edge Cases & Common Mistakes

  • Empty or all spaces: no digits, return 0.
  • Two signs, like "+-12": only one sign is read; the second stops the parse, so the answer is 0.
  • Spaces after the sign: "- 12" is 0, because spaces are only skipped at the very start.
  • Overflow: checking after result * 10 + digit overflows a 32-bit int first; check before.
  • Leading zeros: "0000012" is 12; they add nothing.
  • Using a library parser: most of them accept or reject different inputs than atoi, so write the rules out.

Summary

Skip leading spaces, read at most one sign, then read digits while guarding against overflow before each multiply. Stop at the first non-digit and return sign * result. O(n) time, O(1) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Skip spaces

    Move the index past any leading spaces.

  2. Read a sign

    If the next character is + or -, record the sign and move on once.

  3. Read digits with a guard

    For each digit, return the clamped limit if result * 10 + digit would pass 2^31 - 1; otherwise add it. Stop at the first non-digit and return sign * result.

Frequently asked questions

Why check for overflow before multiplying?

In a 32-bit int, result * 10 + digit can already be too large to store, so checking afterwards is too late. Comparing result with INT_MAX / 10 first tells you whether the next digit would push past 2147483647 without ever computing the overflowing value.


Why is the digit compared with 7?

INT_MAX is 2147483647, so INT_MAX / 10 is 214748364 and its last digit is 7. If result already equals 214748364, any digit above 7 overflows. For negative numbers the limit is 2147483648, and returning INT_MIN for an 8 or 9 gives the right answer in both cases.


What stops the parse?

The first character that is not part of the number: after the spaces and at most one sign, anything that is not a digit ends the read. A second sign, a letter, a dot or a space all stop it, and if no digit was read the answer is 0.


Is this a two pointers problem?

It is a single index walking the string once, the same scanning skill as Add Strings or Multiply Strings. The difficulty is not the algorithm but following every rule in the right order.

New to the technique behind this problem? Watch it run step by step:

Two Pointers Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description