String to Integer (atoi)
MediumParse sign and digits, clamp to range
Read digits one by one from the front, skipping spaces and a sign, and stop at the first non-digit.
The idea
Skip leading spaces, read an optional sign, then consume digits building the number. Stop at the first non-digit and clamp the result to the 32-bit integer range.
-
4
2
x
0
1
2
3
Step 1 of 5. atoi("-42x"): skip spaces, read sign, then digits. Values: -, 4, 2, x.
1/5
Optimal
timeO(n)spaceO(1)
Boundary-checked scan.
1let i = 0, sign = 1, num = 0;2while (s[i] === " ") i++;3if (s[i] === "+" || s[i] === "-") sign = s[i++] === "-" ? -1 : 1;4while (isDigit(s[i])) num = num * 10 + (+s[i++]);5return clamp(sign * num, INT_MIN, INT_MAX);Input
- array
- [-, 4, 2, x]
Memory
- sign
- —
- num
- —
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- s = "42"
- Output:
- 42
- Explanation:
- Straightforward: 42.
Example 2
- Input:
- s = " -42"
- Output:
- -42
- Explanation:
- Skip spaces, honour the minus → -42.
Example 3
- Input:
- s = "4193 with words"
- Output:
- 4193
- Explanation:
- Read digits until letters stop it → 4193.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.