LeetCode 8. String to Integer (atoi)
Implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi function).
The algorithm for myAtoi(string s) is as follows:
Read in and ignore any leading whitespace.
Check if the next character (if not already at the end of the string) is '-'
or '+'
. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
Read in next the characters until the next non-digit charcter or the end of the input is reached. The rest of the string is ignored.
Convert these digits into an integer (i.e. “123” -> 123, “0032” -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1]
, then clamp the integer so that it remains in the range. Specifically, integers less than -2^31
should be clamped to -2^31
, and integers greater than 2^31 - 1
should be clamped to 2^31 - 1
.
Return the integer as the final result.
Note:
Only the space character ' '
is considered a whitespace character.
Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
Example 1:
Input: s = "42"
Output: 42
Example 2:
Input: s = " -42a"
Output: -42
method
先找到第一个字符的位置,判断正负号,再读取每个数字字符整合在一起
判断溢出逻辑:整数范围是-21,4748,3648
到21,4748,3647
,如果一个数已经大于21,4748,364
,那再来一位什么数都会溢出。
或者一个数等于21,4748,364
,再来一位大于7的数就会溢出,虽然负数的话,来个8也行,但这里就算来8,输出的也是-21,4748,3648
,所以一起当成溢出处理
int myAtoi(string s) {
int sign = 1, base = 0; // 符号和数值
int i = 0; // 遍历的指针
while (i < s.size() && s[i] == ' ') i++; // 找到第一个字符
if (i == s.size()) return 0;
if (s[i] == '-' || s[i] == '+') {
if (s[i] == '-') {
sign = -1;
}
i++;
}
while (i < s.size() && s[i] >= '0' && s[i] <= '9') {
int num = s[i] - '0';
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && num > 7)) {
if (sign == 1) return INT_MAX;
else return INT_MIN;
}
base = base * 10 + num;
i++;
}
return sign * base;
}