← DiffPush

Implement atoi

Standard Bar Strings · Medium O(n) · O(1)

Field Parser on a Noisy Boot Bus

An embedded controller reads configuration tokens off a serial bus where sensor firmware appends free-form annotations around the numeric fields. The parser must behave like the C library: skip leading blanks, honour one sign character, consume the digit run, ignore everything after it, and saturate at the 32-bit register bounds instead of wrapping. A field that never reaches a digit yields zero.

Input: A string s that may contain leading spaces, an optional '+' or '-' sign, digits, and arbitrary trailing characters.

Output: The parsed 32-bit signed integer: digits read with their sign, clamped to [-2^31, 2^31 - 1] on overflow, or 0 when no digits are read.

Constraints

Examples

Example 1

Input: {"s":"42"}
Output: 42
No blanks, no sign — the digit run is read straight through.

Example 2

Input: {"s":" -42"}
Output: -42
The leading blank is skipped and the '-' fixes the sign before the digits are consumed.

Solve this in your browser →

Also on LeetCode ↗