
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.
1using System;
2
3public class Solution {
4 public int MyAtoi(string s) {
5 int i = 0, sign = 1, n = s.Length;
6 while (i < n && s[i] == ' ') i++;
7 if (i < n && (s[i] == '+' || s[i] == '-'))
8 sign = (s[i++] == '-') ? -1 : 1;
9 long result = 0;
10 while (i < n && char.IsDigit(s[i])) {
11 result = result * 10 + (s[i++] - '0');
12 if (result * sign > int.MaxValue) return int.MaxValue;
13 if (result * sign < int.MinValue) return int.MinValue;
14 }
15 return (int)(result * sign);
16 }
17
18 public static void Main() {
19 Solution sol = new Solution();
20 Console.WriteLine(sol.MyAtoi("-42"));
21 Console.WriteLine(sol.MyAtoi("4193 with words"));
22 Console.WriteLine(sol.MyAtoi("words and 987"));
23 Console.WriteLine(sol.MyAtoi("-91283472332"));
24 }
25}The C# implementation handles the conversion similarly by ignoring leading whitespace, checking the sign, iterating over digits while updating a long variable 'result'. It conditions against overflow and underflow when returning the final integer.
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.