题目描述:
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.
spoilers alert... click to show requirements for atoi.
Hide Tags Math String
分析:
本题思路很简单,但是要考虑的细节相当多.
要判断一个字符串是否能转换成整数:首先必须是数字字符和首部可能含有符号字符,而且还要判断是否越界。整数范围是[INT_MIN,INT_MAX]
1、首先应该要去掉首部的所有空格
2、判断符号:若第一个空字符是'+'或'-',那么记录符号flag;
3、从第一个非空符号的下一个元素开始,用整型的res来保存结果,循环处理:首先判断是否为数字字符,若不是,则退出循环;否则更新res,每次更新res之前,都要先判断更 新会不会越界,若不不越界,就更新,否则就根据flag返回最大值或最小值。
4、最后返回flag*res;
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.
spoilers alert... click to show requirements for atoi.
Hide Tags Math String
分析:
本题思路很简单,但是要考虑的细节相当多.
要判断一个字符串是否能转换成整数:首先必须是数字字符和首部可能含有符号字符,而且还要判断是否越界。整数范围是[INT_MIN,INT_MAX]
1、首先应该要去掉首部的所有空格
2、判断符号:若第一个空字符是'+'或'-',那么记录符号flag;
3、从第一个非空符号的下一个元素开始,用整型的res来保存结果,循环处理:首先判断是否为数字字符,若不是,则退出循环;否则更新res,每次更新res之前,都要先判断更 新会不会越界,若不不越界,就更新,否则就根据flag返回最大值或最小值。
4、最后返回flag*res;
以下是C++实现代码:
/*//8ms*/
class Solution {
public:
int myAtoi(string str) {
if(str.empty())
return 0;
int i = 0;
while(isspace(str[i]))
i++;
int flag = str[i] == '-' ?-1:1;
if(str[i] == '-' || str[i] == '+')
i++;
int res = 0;
for(; i < str.size();i++)
{
if(isdigit(str[i]))
{
if(INT_MAX /10 >= res)
res *= 10;
else
return (flag==-1)? INT_MIN: INT_MAX;
if(INT_MAX - (str[i] - '0') >= res)
res += (str[i] - '0');
else
return (flag==-1)? INT_MIN: INT_MAX;
}
else
break;
}
return res * flag;
}
};