String to Integer (atoi)

Medium · Math & Number Theory · about 20 minutes

Asked at Amazon, Microsoft, Google, Bloomberg, Meta, Netflix, D. E. Shaw.

Write myAtoi(s) to read a signed 32-bit integer from the front of a string:

  • Skip any spaces at the start (only ' ').
  • Accept one optional '+' or '-'.
  • Collect digits until you hit a non-digit or the end of the string; leading zeros don't matter. No

digits at all means the result is 0.

  • If the value is below −2³¹ or above 2³¹ − 1, clamp it to that bound.

Anything after the digits is ignored.