这道题考虑了很久
1 有+ - 符号出现,用is_negetive记录了正负情况,
2.出现多个+-或者其他符号,返回0;
3.出现空格则返回控各前的数。
4.空格和符号一起出现,如" +5205"
5.出现溢出情况。这个比较难,在int范围是2的32次方-1到负2的32次方。比较是否超出这两个范围,如果超出则返回最大值或最小值。
PS:我是用的DEV C++编译器,在这里min=-2147483648;会出现错误[Warning] this decimal constant is unsigned only in ISO C90 ,这时候将-2147483648用十六进制表示。
class Solution {
public:int myAtoi(string str) {
long num=0;
int i=0;
int is_negetive=0;
int max=2147483647;
long min=-2147483648;
while(i<str.length()&&str[i]==' '){
i++;
}
while(i<str.length()){
if(((str[i]-'0')<0||(str[i]-'0')>9)){
if(str[i]=='-'&&is_negetive==0){
is_negetive=-1;}
else if(str[i]=='+'&&is_negetive==0){
is_negetive=1;}
else
break;
}
else if((str[i]-'0'<=9)&&(str[i]-'0'>=0)){
if(is_negetive>=0){
num=num*10+(str[i]-'0');
if(num>max)
return max;
}
else if(is_negetive<0){
num=num*10-(str[i]-'0');
if(num<min)
return min;
}
}
i++;
}
return num;
}
};