
Sponsored
Sponsored
In this approach, we manually parse the string character by character. First, we skip any leading whitespace. Then, we determine the sign of the number by checking the next character. After we've set up the sign, we convert succeeding string characters to a number as long as they are digits, and check if the number overflows the 32-bit signed integer range. The iterative parsing continues until we encounter a non-numeric character.
Time Complexity: O(n), where n is the length of the string because we traverse the string once.
Space Complexity: O(1), since we only use a fixed amount of extra space.
1class Solution:
2 def myAtoi(self, s: str) -> int:
3 i, sign, result = 0, 1, 0
4 n = len(s)
5 while i < n and s[i] == ' ': i += 1
6 if i < n and s[i] in ['+', '-']:
7 sign = -1 if s[i] == '-' else 1
8 i += 1
9 while i < n and s[i].isdigit():
10 result = result * 10 + int(s[i])
11 i += 1
12 if result * sign > 2**31 - 1: return 2**31 - 1
13 if result * sign < -2**31: return -2**31
14 return result * sign
15
16# Example usage:
17sol = Solution()
18print(sol.myAtoi("-42"))
19print(sol.myAtoi("4193 with words"))
20print(sol.myAtoi("words and 987"))
21print(sol.myAtoi("-91283472332"))In Python, the approach remains consistent with the C and Java implementations, though syntactically streamlined. Initial conditions are set, including ignoring whitespace and determining the sign. The conversion loop runs over numeric digits, and checks for overflows before returning a final integer result.
Using regular expressions simplifies extracting the integer portion from a string. This involves defining a regular expression to match the pattern for potential number initializations, determining whether followed by valid digits until non-numeric encounters or string end, and then mathematically transforming results. While elegant, care still needs to be taken on handling sign and range boundaries.
Time Complexity: O(n), regular expression parsing inspects the input sequence linearly.
Space Complexity: O(1), denoting the small constant space taken up by the quantitative calculation.
1import re
2
3class
Leveraging Python's regex library, we employ an expression that recognizes number-related input starting with whitespace/signs, combining matched string outcomes into an integer. Compared to other manual parsing routines, this method highlights reductionism while maintaining integrity on output values.