题目:
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.
分析:
题目其实不难,不过需要注意下面几点:
- 字符串前的空白
- 字符串所表示数值的正负号
- 结束条件,遇到非数字或者字符’\0’结束
- 考虑溢出,与int值所能表示的最大(0x7fffffff)和最小值进行比较
- 考虑异常输入情况下,用全局变量valid来标识,对于”+/-” “0” “+abc”需要进行区分
- 还有就是测试过程中发现的对于“+-2”的处理是返回0;对于超出范围的数,如果是正数则将其置为(0x7fffffff), 如果为负数则将其置为(- 0x7fffffff – 1)。
代码:
class Solution {
public:
int atoi(const char *str) {
//正负数标识
bool flag = false;
//作为负数是否小于0x80000000的标识
int tmin = 0;
long long sum = 0;
//判断字符串是否为空
if(str == NULL)
return 0;
//去除前置空格
while(*str == ' ')
str++;
//判断数的符号,当时以为可以有多个符号取最后一个呢,后来发现只允许一个符号位
if(*str == '-'){
flag = true;
str++;
}
else if(*str == '+'){
str++;
}
//判断数的合法性
if(*str < '0'|| *str >'9')
return 0;
//处理有效字符的值
while(*str>='0'&&*str<='9'){
sum = sum * 10 + *str -'0' ;
//判断是否超过了规定的范围
if( !flag && sum > (int)0x7FFFFFFF){
sum = (int)0x7FFFFFFF;
break;
}else if( flag && sum > (int)0x7FFFFFFF){
sum = (int)0x7FFFFFFF;
tmin = 1;
break;
}
str++;
}
//判断数的符号
if(flag&&tmin)
sum = -sum-1;
else if(flag&&!tmin)
sum = -sum;
return sum;
}
};