String to Integer (atoi) 题解
题目来源:https://leetcode.com/problems/string-to-integer-atoi/description/
Description
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
**Notes:** It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Solution
class Solution {
public:
int myAtoi(string str) {
int res = 0, i = 0;
bool positive = true;
while (str[i] == ‘ ‘) i++;
if (str[i] == ‘-‘ || str[i] == ‘+‘) {
positive = str[i] == ‘+‘;
i++;
}
while (str[i] >= ‘0‘ && str[i] <= ‘9‘) {
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && str[i] - ‘0‘ > 7)) {
return positive ? INT_MAX : INT_MIN;
}
res = res * 10 + (str[i] - ‘0‘);
i++;
}
return positive ? res : -res;
}
};
解题描述
这道题考察的是字符串转数字函数atoi
的实现。最主要要解决的几个问题是:
- 忽略数字前面的空格
- 正负号判断
- 溢出判断
- 非法输入的判断
其中非法输入的判断在上面给出的解中是通过判断字符ASCII范围来判断的。