Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

47. String to Integer (atoi)

MediumDay 15 of 60Strings

Implement myAtoi(s), which turns a string into a 32-bit signed integer the way C's atoi does. Skip leading spaces, then read an optional + or - sign, then read digits until the first non-digit character (ignore the rest). If no digits were read, the result is 0. If the number is outside the range [-2^31, 2^31 - 1], clamp it to the nearest end of that range.

Example 1
Input: s = " -42"
Output: -42
Spaces are skipped, the minus sign is read, then the digits 42.
Example 2
Input: s = "4193 with words"
Output: 4193
Reading stops at the space after the digits.
Constraints
  • 0 <= s.length <= 200
  • `s` has English letters, digits, spaces, `+`, `-` and `.`
Hints
Frequently asked at: Microsoft, Amazon, Meta, Goldman Sachs
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min