19. String to Integer (atoi)

19. String to Integer (atoi)

Medium
39.0%
1.7k
stringmath
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

You’re interviewing for a backend or data engineering role at a FAANG level company. The interviewer describes a real product scenario:

A large scale platform ingests text input from users, APIs, logs, and third party systems. These inputs often contain numeric values encoded as strings, sometimes with leading spaces, optional signs, or trailing non numeric characters.

Before storing or processing this data, the system needs to safely convert a string into a 32 bit signed integer while following strict parsing rules to avoid crashes, incorrect values, or overflow issues.

This is a common practice coding problem for DSA question might ask in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.

Your Task

Implement a function that converts a string s into a 32 bit signed integer.

The conversion must follow these rules in order:

  1. Ignore any leading whitespace characters
  2. Check for an optional plus or minus sign
  3. Read digits until a non digit character is encountered
  4. If no digits are read, return 0
  5. Clamp the result within the 32 bit signed integer range

Input Format

  • s: a string representing a number with optional spaces and sign

Output Format

  • A single integer representing the parsed value after applying all rules

Examples

Example 1:

Input: s = "42"
Output: 42

Example 2:

Input: s = " -42"
Output: -42

Example 3:

Input: s = "4193 with words"
Output: 4193

Example 4:

Input: s = "words and 987"
Output: 0

Example 5:

Input: s = "-91283472332"
Output: -2147483648

Constraints

  • 0 <= s.length <= 200
  • s may contain letters, digits, spaces, plus sign, and minus sign
  • Valid integer range is from -2^31 to 2^31 - 1

Loading editor...

"42"
42

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback