MediumStringsMath

String to Integer (atoi)

LeetCode
1 approach, code in all languages

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 <= 200
  • s consists of spaces, digits, letters, '+', '-', and '.'
  • The final value is clamped to the range [-2^31, 2^31 - 1]
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now