Leetcode 8. String to Integer (atoi)
The task is to implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi
function).
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus (+
) or minus (-
) sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in s
is not a valid integral number, or if no such sequence exists because the string is empty or contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
If the numerical value is out of the range of a 32-bit signed integer, then:
INT_MAX
(2147483647) if the value is positive.INT_MIN
(-2147483648) if the value is negative.INT_MAX
or INT_MIN
depending on the sign of the number.+
or -
to determine the sign, otherwise assume it’s a positive number.INT_MAX
or INT_MIN
if necessary.#include <string>
#include <climits>
class Solution {
public:
int myAtoi(std::string s) {
int i = 0;
int n = s.size();
// Step 1: Ignore leading whitespaces
while (i < n && s[i] == ' ') {
i++;
}
// Step 2: Check if the next character is '+' or '-'
int sign = 1;
if (i < n && (s[i] == '+' || s[i] == '-')) {
sign = (s[i] == '-') ? -1 : 1;
i++;
}
// Step 3: Convert subsequent numerical characters to integer
long long result = 0;
while (i < n && isdigit(s[i])) {
result = result * 10 + (s[i] - '0');
// Step 4: Handle overflow
if (result * sign > INT_MAX) return INT_MAX;
if (result * sign < INT_MIN) return INT_MIN;
i++;
}
return static_cast<int>(result * sign);
}
};
n
is the number of characters in the string. In the worst case, we traverse the string once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?