问题来源:https://leetcode.com/problems/string-to-integer-atoi/
这道题目,不看她给的要求根本做不出来啊。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.
Update (2015-02-10):
The signature of theC++
function had been updated. If you still see your function signature accepts aconst char *
argument, please click the reload button to reset your code definition.spoilers alert... click to show requirements for atoi.
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.
注意的几点:
1. 去除开头所有的空格
2. 开头第一个字符有可能是+或者-,可以判断正负数。
3. 接下来的所有数字都会成为int的某一部分,如果碰到非数字直接break
4. 计算过程中,注意是否超过界限。
class Solution {
public:
int myAtoi(const string str) {
if (str.size() == 0)
return 0;
int i = 0;
long long rs = 0;
int flag = true;//正负数
for (; i < str.size(); i++)//去除开头的所有空格
{
if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n')
;
else
break;
}
if (i < str.size())//判断正负数
{
if (str[i] == '-')
{
flag = false;
i++;
}
else if (str[i] == '+')
i++;
}
while (i < str.size())
{
if (str[i] >= '0' && str[i] <= '9')
{
rs = rs * 10 + (str[i] - '0');
if (rs >= 2147483648)//当rs太大的时候,直接返回int的最大值或者最小值即可
{
if (flag)
rs = 2147483647;
else
rs = 2147483648;
break;
}
i++;
}
else
break;
}
if (!flag)
return rs*-1;
return rs;
}
};