题目描述
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.
spoilers alert... click to show 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.
分析:将字符串转换为数值,函数库 stoi的编写:主要考虑空白字符、正负号、溢出、非法字符停止等条件
class Solution {
public:
int atoi(const char *str)
{
string s(str);
int len = s.length(),flag = 1;
long res = 0L;
int index = s.find_first_not_of(' ');
if(s[index] == '+' || s[index] == '-')
flag = s[index++]=='-' ? -1 : 1;
for(;index<len;index++)
{
if(s[index] >='0' && s[index] <= '9')
{
res = res*10 + (s[index]-'0');
if(res *flag >= INT_MAX) return INT_MAX;
if(res *flag <= INT_MIN) return INT_MIN;
}
else
break;
}
return res*flag;
}
};
类似题:剑指offer 把字符串转换成整数