LeetCode 8 - String to Integer (atoi)
Table of Contents
Problem Statement
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:
Whitespace: Ignore any leading whitespace (“ “).
Signedness: Determine the sign by checking if the next character is ‘-‘ or ‘+’, assuming positivity if neither present.
Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result.
Using Finite State Machine (FSM)
Explanation
The myAtoi() function converts a string to an integer following the Finite State Machine (FSM) pattern. The process consists of five distinct states:
- Ignore Leading Whitespaces
- Skip all leading spaces using:
1 2 3
while (i < n && s[i] == ' ') { ++i; }
- Moves to the next state when a non-space character is found.
- Skip all leading spaces using:
- Determine the Sign
- If
s[i] == '+', setsign = 1. - If
s[i] == '-', setsign = -1. - Move to the next character.
- If
- Convert Digits to an Integer
- If
isdigit(s[i]), accumulate the number:1
result = result * 10 + (s[i] - '0');
- If a non-digit is found, stop processing.
- If
- Handle Overflow
- Since
resultis of typelong long, we check:1 2
if (result * sign > INT_MAX) return INT_MAX; if (result * sign < INT_MIN) return INT_MIN;
- This clamps the number within the 32-bit integer range.
- Since
- Return the Final Value
- Multiply
resultbysignand return the integer.
- Multiply
Finite State Machine (FSM) Diagram
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int myAtoi(string s) {
int i = 0, n = s.length();
while (i < n && s[i] == ' ') {
++i;
}
int sign = 1;
if (i < n && (s[i] == '-' || s[i] == '+')) {
sign = (s[i] == '-') ? -1 : 1;
++i;
}
long long result = 0;
while (i < n && isdigit(s[i])) {
result = result * 10 + (s[i] - '0');
if (result * sign > INT_MAX) return INT_MAX;
if (result * sign < INT_MIN) return INT_MIN;
++i;
}
return result * sign;
}
};
Conclusion
- Time Complexity: 𝑂(𝑛) — The function processes each character in the string at most once, and the while loops iterate through the string linearly, where n is the length of the input string.
- Space Complexity: 𝑂(1) — The function does not use extra space that grows with the input size, only using a few integer variables.
