Leetcode 8: String to Integer (atoi)

grid47
grid47
Exploring patterns and algorithms
Nov 6, 2024 6 min read

A glowing number forming from abstract text, transforming from letters to digits.
Solution to LeetCode 8: String to Integer (atoi) Problem

Convert a string to a 32-bit signed integer, handling whitespaces, optional signs, and non-digit characters.
Problem
Approach
Steps
Complexity
Input: The input is a string s containing English letters, digits, spaces, and optional signs.
Example: s = ' 42'
Constraints:
• 0 <= s.length <= 200
• s consists of English letters (lowercase and uppercase), digits (0-9), spaces, '+' or '-', and possibly other non-digit characters.
Output: Return the integer value represented by the string after ignoring leading spaces and processing digits, within the 32-bit signed integer range.
Example: For input s = '42', the output is 42.
Constraints:
• The result must be within the range of a 32-bit signed integer: [-231, 231 - 1].
Goal: Parse the string, handle optional signs, ignore non-digit characters after the first integer, and ensure the result remains within the 32-bit signed integer limits.
Steps:
• Skip leading spaces.
• Check for a '+' or '-' sign to determine the number's sign.
• Parse the digits until a non-digit character is encountered.
• If no digits are found, return 0.
• Clamp the result to fit within the 32-bit signed integer range.
Goal: Handle edge cases such as empty strings, leading spaces, and large numbers.
Steps:
• The string may have leading or trailing spaces.
• The string may contain a sign before the number.
• The number may exceed the 32-bit signed integer range.
Assumptions:
• The input string can contain digits, spaces, signs, and other characters.
• If no valid number is found, the result should be 0.
Input: Example 1: s = ' 42'
Explanation: The function processes the string '42', ignoring leading spaces, and returns the integer 42.

Input: Example 2: s = ' - 0345'
Explanation: The function reads the number '-345' after ignoring the spaces and the leading zeros.

Input: Example 3: s = '56x89'
Explanation: The function reads '56' and stops at the character 'x', returning 56.

Input: Example 4: s = '0000000000'
Explanation: All zeros are ignored, resulting in 0.

Input: Example 5: s = 'words 123'
Explanation: Since the string starts with non-numeric characters, the function returns 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus