String to Integer (atoi) - Problem

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer following these rules:

  1. Whitespace: Ignore any leading whitespace characters
  2. Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present
  3. Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0
  4. Rounding: If the integer is out of the 32-bit signed integer range [-2³¹, 2³¹ - 1], then clamp the integer to remain in the range

Return the integer as the final result.

Input & Output

Example 1 — Basic Negative Number
$ Input: s = "42"
Output: 42
💡 Note: Simple case: skip no whitespace, no sign, convert digits "42" to integer 42
Example 2 — Whitespace and Sign
$ Input: s = " -42"
Output: -42
💡 Note: Skip leading spaces, parse negative sign, convert "42" and apply sign to get -42
Example 3 — Mixed Characters
$ Input: s = "4193 with words"
Output: 4193
💡 Note: Convert "4193" until space character encountered, ignore remaining characters

Constraints

  • 0 ≤ s.length ≤ 200
  • s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'

Visualization

Tap to expand
String to Integer (atoi) INPUT String s = "42" " 4 2 " idx 0 idx 1 pointer Input Details: s = "42" Length: 2 characters 32-bit range: [-2147483648, 2147483647] [-2^31, 2^31 - 1] ALGORITHM STEPS 1 Skip Whitespace No leading spaces in "42" index = 0 2 Check Sign No +/- found sign = +1 (default) 3 Read Digits Process '4' --> result=4 Process '2' --> result=42 result = 0*10 + 4 = 4 result = 4*10 + 2 = 42 4 Clamp Result 42 is within range No clamping needed Single Pass Approach: Stop at first non-digit Check overflow before multiply FINAL RESULT Converted Integer: 42 OK Output Details: 42 Type: 32-bit signed int Sign: positive Within valid range -2147483648 <= 42 <= 2147483647 Key Insight: The optimized single pass approach processes characters sequentially, checking for overflow BEFORE each multiplication. Early termination occurs at first non-digit, avoiding unnecessary iterations. Time: O(n) | Space: O(1) | where n = string length TutorialsPoint - String to Integer (atoi) | Optimized Single Pass with Early Termination
Asked in
Amazon 45 Google 38 Facebook 32 Microsoft 28
89.3K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen