
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.
1#include <stdio.h>
2#include <limits.h>
3
4int myAtoi(char * s) {
5 int i = 0, sign = 1;
6 while (s[i] == ' ') i++;
7 if (s[i] == '-' || s[i] == '+')
8 sign = (s[i++] == '-') ? -1 : 1;
9 long result = 0;
10 while (s[i] >= '0' && s[i] <= '9') {
11 result = result * 10 + (s[i++] - '0');
12 if (result * sign > INT_MAX) return INT_MAX;
13 if (result * sign < INT_MIN) return INT_MIN;
14 }
15 return (int)(result * sign);
16}
17
18int main() {
19 printf("%d\n", myAtoi(" -42"));
20 printf("%d\n", myAtoi("4193 with words"));
21 printf("%d\n", myAtoi("words and 987"));
22 printf("%d\n", myAtoi("-91283472332"));
23 return 0;
24}The function begins by traversing any leading whitespace in the input string. If the next character is a '-' or '+', it sets the sign accordingly and moves to the next character. We update a 'result' variable as we iterate over each digit, checking against overflow conditions. This result is carefully treated as a long to avoid overflow, then cast to an int at the end. Edge cases, including overflow beyond 32-bit bounds, are also managed explicitly.
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.
1var myAtoi = function(s)
This JavaScript function utilizes a regular expression to detect any leading spaces, an optional sign, and a sequence of digits at the start of the string. The parseInt utility parses the integer, which is tempered by limits for overflowing numbers using conditional returns.