问题描述
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.
问题分析
和leetcode007的题目用到的点基本相同,只是有些情况在运行测试后发现的,如“ +5df”这样的字符串是5,要考虑到,而不是返回错误,ok,直接上代码。
代码
class Solution {
public:
int atoi(string str) {
int i = 0;
while (i < str.length() && str[i] == ' ') { i++; }
str = str.substr(i);
if (str.length() <= 0) return 0;
char arr[13];//选择13的目的是int型10进制最大值位数为10位,加上符号位为11位,防止溢出。
int flag = 0;
for (i = 0; i < 12 && i < str.length(); i++)
{
if (i == 0 && (str[i] == '-' || str[i] == '+') || str[i] >= '0' && str[i] <= '9') arr[i] = str[i];
else break;
}
arr[i] = '\0';
int len = strlen(arr);
if (!len || len == 1 && (arr[0] == '+' || arr[0] == '-')) return 0;
long long k;
sscanf(arr, "%lld", &k);
if (k > INT_MAX) k = INT_MAX;
if (k < INT_MIN) k = INT_MIN;
return k;
}
};