Implement atoi to convert a string to an integer.
Requirements for atoi:
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 str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
坑有点多,要考虑到所有情况,从正负号(如果有的话)之后遇到不是数字的字符就结束。我是先用字符串把整理过后标准的形式存起来,然后用字符串的比较来判断是否溢出。
class Solution {
public:
int myAtoi(string str) {
string s, int_max("2147483647"), int_min("2147483648");
int i = 0, p = 1;
int res = 0;
while (str[i] == ' ')
i++;
if(str[i] == '+')
i++;
else if(str[i] == '-'){
p = -1;
i++;
}
if(str[i] < '0' || str[i] > '9')
return 0;
for(; i < str.size(); i++){
if(str[i] >= '0' && str[i] <= '9')
s += str[i];
else
break;
}
if(p == 1){
if(s.size() > int_max.size() || ((s.size() == int_max.size())&&s >= int_max))
return 2147483647;
}
if(p == -1){
if(s.size() > int_max.size() || ((s.size() == int_max.size())&&s >= int_min))
return -2147483648;
}
for(int k = 0; k < s.size(); k++){
res = res*10 + (s[k]-'0');
}
res = res * p;
return res;
}
};