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.
思路分析:
将一个字符串转化为整数。考虑输入情况:
- 输入有空格(若空格在最前面或最后面,忽略空格;若空格在字符中间,比如“ 0012 a34”,返回为空格前面的计算结果,即12);
- 正负数:第一个有效字符为数字或者“+”,是正数。第一个有效字符如果为“-”,是负数。若其他字符为非数字字符,则返回该字符前面的计算结果;
要注意的点:
结果应用long型存储,防止越界。最后转化为int型;
class Solution {
public:
int myAtoi(string str) {
if(str.length() == 0) return 0;
long sum = 0;
bool isPositive = true;//默认为正数
int i = 0;
for( ; i < str.length(); ){//过滤最初的空格或者符号位
if(str[i] == ' '){
i ++;
continue;
}
else if(str[i] == '-'){
isPositive = false;
i ++;
break;
}
else if(str[i] == '+'){
i ++;
break;
}
else
break;//如果第一个字符为数字,则不做任何动作,进入下面的计算
}
for( ; i < str.length(); i ++){
// if(str[i] == ' ' || str[i] == '-' || str[i] == '+' || !isdigit(str[i]) ){//输入不合格
if(!isdigit(str[i]) ){
break;
}
if(isPositive){
sum = sum * 10 + str[i] - '0';
if(sum >= INT_MAX) return INT_MAX;
}
else{
sum = sum * 10 - (str[i] - '0');
if(sum <= INT_MIN) return INT_MIN;
}
}
return sum;
}
};