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.
class Solution {
public:
int myAtoi(string str) {
int sign = 1, i = 0, ans = 0;
while(str[i] == ' ') ++i;
if(str[i] == '-' || str[i] == '+')
{
sign = 1 - 2*(str[i++] == '-');
}
while(str[i] >= '0' && str[i] <= '9')
{
if (ans > INT_MAX / 10 || (ans == INT_MAX / 10 && str[i] - '0' > 7)) {
if (sign == 1) return INT_MAX;
else return INT_MIN;
}
ans = 10 * ans + (str[i++] - '0');
}
return ans * sign;
}
};
这两个方法 一个先判断是否越界,一个后判断是否越界,下面的后判断是否越界的,如果ans定义成int 然后后判断,会出现错误!先溢出! 所以下面定义成long long 才可以!
class Solution {
public:
int myAtoi(string str) {
int sign = 1, i = 0;
long long ans = 0;
while(str[i] == ' ') ++i;
if(str[i] == '-' || str[i] == '+')
{
sign = 1 - 2*(str[i++] == '-');
}
while(str[i] >= '0' && str[i] <= '9')
{
ans = 10 * ans + (str[i++] - '0');
if (ans > INT_MAX ) {
if (sign == 1) return INT_MAX;
else return INT_MIN;
}
}
return ans * sign;
}
};
本文介绍了一种将字符串转换为整数的有效方法,并通过两个不同的C++实现展示了如何正确处理边界条件,避免整数溢出的问题。
508

被折叠的 条评论
为什么被折叠?



