Convert a string into a signed 32-bit integer by scanning it the way a hand-written parser would. First skip any leading spaces, then read an optional single plus or minus sign, then collect the run of decimal digits that follows. Reading stops at the first character that is not a digit, and everything after that point is ignored.
If no digits appear the result is 0. When the assembled number falls outside the signed 32-bit range, clamp it: values below the minimum become -2^31 and values above the maximum become 2^31 - 1.
Example 1
Input: s = " -042"
Output: -42
Leading spaces are skipped, the minus sign is recorded, and the leading zero in 042 is absorbed to give -42.
Example 2
Input: s = "4193 with words"
Output: 4193
Digits are gathered until the space, so the trailing text is discarded.
Constraints
0 <= s.length <= 200s consists of spaces, digits, letters, '+', '-', and '.'The final value is clamped to the range [-2^31, 2^31 - 1]See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI