
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.
1public class Solution {
2 public int myAtoi(String s) {
3 int i = 0, sign = 1, len = s.length();
4 while (i < len && s.charAt(i) == ' ') i++;
5 if (i < len && (s.charAt(i) == '+' || s.charAt(i) == '-'))
6 sign = (s.charAt(i++) == '-') ? -1 : 1;
7 long result = 0;
8 while (i < len && Character.isDigit(s.charAt(i))) {
9 result = result * 10 + (s.charAt(i++) - '0');
10 if (result * sign > Integer.MAX_VALUE) return Integer.MAX_VALUE;
11 if (result * sign < Integer.MIN_VALUE) return Integer.MIN_VALUE;
12 }
13 return (int) (result * sign);
14 }
15 public static void main(String[] args) {
16 Solution sol = new Solution();
17 System.out.println(sol.myAtoi("-42"));
18 System.out.println(sol.myAtoi("4193 with words"));
19 System.out.println(sol.myAtoi("words and 987"));
20 System.out.println(sol.myAtoi("-91283472332"));
21 }
22}This Java code shares the same fundamental logic with its C and C++ counterparts. It uses a while-loop to consume leading whitespace, checks for an optional sign, and then processes any digits, using a long to temporarily store results and handle potential overflows before returning an int.
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.