题目源自于Leetcode。
思路:
一定要考虑所有的情况。
一、合法性检查
1、输入字符型指针是否指向空?
2、输入字符串内是否有非阿拉伯数字?(是否允许字符串开头有空格?是否允许字符串后面出现其他字符?)
二、特殊情况
1、正负数情况
2、溢出情况的判断:这里我用的是一个64位整型数来帮忙的。
INT_MAX (2147483647) 和 INT_MIN (-2147483648) 是c语言默认的宏,表示int可表示的最大和最小值(记住是个10位数)。
3、字符串开头是0的情况
代码:
#include <cstdio>
#include <iostream>
using namespace std;
class Solution {
public:
int atoi(const char *str) {
if(str == NULL)
return 0;
int result;
long long data = 0;
int sign = 1;
int i=0;
while(str[i] == ' ')
i++;
if(str[i] == '-')
{
sign = -1;
i++;
}
else if(str[i] == '+')
{
sign = 1;
i++;
}
while(str[i] != '\0')
{
if(str[i]<'0' || str[i] > '9')
break;
data *= 10;
data += str[i] - '0';
if(data > INT_MAX) //溢出判断
{
if(sign == 1)
return INT_MAX;
else
return INT_MIN;
}
i++;
}
result = (int)data;
if(sign == -1)
result = - result;
return result;
}
};
int main()
{
char a[] = "10522545459";
Solution s;
int b = s.atoi(a);
cout<<b<<endl;
return 1;
}