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 the C++
function had been updated. If you still see your function
signature accepts a const char *
argument, please click the reload button to
reset your code definition.
唉·,没想到这么简单一个都这么难写。
注意四点情况:
1.输入为空
2.正负号
3.数据溢出
4.空白格
数据溢出不好弄,下面这个方法是利用INT_MAX/10的值和当前result未乘10的值进行比较,判断是否溢出。由于溢出正负极值分别为2147483647 -2147483648,所以为了简练,有两种情况:(1)直接大于INT_MAX/10,说明足够大了,绝对溢出了(2)等于INT_MAX/10,可能会溢出,我们需要再加一个条件判断,是否最后一位大于7。对于正数,2147473648即为最小的溢出值,最后一位大于7。对于负值,如果值为2147483648,虽然没溢出,但是刚好,假设它的值到了这个档次,即时溢出了我们也要返回-2147483648,所以这种情况也应该返回。
class Solution {
public:
int myAtoi(string str) {
if(str.size() == 0)
return 0;
int result = 0;
int sign = 1;
int i = 0;
while(str[i] == ' ')
++i;
if(str[i] == '-' || str[i] == '+')
sign = (str[i++] == '-') ? -1 : 1;
while(str[i] >= '0' && str[i] <= '9'){
if(result > INT_MAX / 10 || (result == INT_MAX / 10 && str[i]-'0' > 7)){
return sign == 1 ? INT_MAX : INT_MIN;
}
result = result * 10 + str[i++] - '0';
}
return result * sign;
}
};