String to Integer (atoi)
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.
class Solution {
public:
int atoi(string str) {
long long result=0;
int flag=1;
int i=0;
while(str[i]==' '&&str[i]!='\0'){
i++;
}
if(str[i]=='-'&&str[i]!='\0'){
flag=0;
i++;
}else if(str[i]=='+'&&str[i]!='\0'){
i++;
}
for(;str[i]!='\0';i++){
if(str[i]>='0'&&str[i]<='9'){
if(flag){
result=result*10+str[i]-'0';
if(result>0x7FFFFFFF)
return 0x7FFFFFFF;
}else{
result=result*10-(str[i]-'0');
if(result<(signed int)0x80000000)
return 0x80000000;
}
}else break;
}
return (int)result;
}
};
注意:
1、字符前的空格处理;
2、无效字符输入
3、整数越界问题,此处使用了小技巧,将返回类型定义为long long。再分开判断是否越界
32位整数范围((signed int) 0x80000000~0x7FFFFFFF)
浙公网安备 33010602011771号