MediumStringsAI interview only
String to Integer (atoi)
Asked atamazonmicrosoftapplegooglemetabloomberggoldman-sachs
01 · Problem
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:
- Whitespace: Ignore any leading whitespace (
" "). - Signedness: Determine the sign by checking if the next character is
'-'or'+', assuming positivity if neither present. - Conversion: Read the integer by skipping leading zeros and stopping at the first non-digit character or at the end of the string.
- Rounding: If the integer is out of the 32-bit signed integer range
[-2^31, 2^31 - 1], clamp the integer to remain in the range.
Return the integer as the final result.
02 · Examples
Example 01
Input
s = " -042"
Output
-42
Leading whitespace is skipped, '-' sets the sign to negative, "042" is read as 42, giving -42.
Example 02
Input
s = "1337c0d3"
Output
1337
Digits "1337" are read. Conversion stops at 'c' which is not a digit.
03 · Constraints
- 010 <= s.length <= 200
- 02s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.
04 · Optimal complexity
- Time
- O(n)
- Space
- O(1)
05 · Two ways to work on it
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.