一、问题描述
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.
二、算法思路
将字符串转化为int,主要考虑以下几种特殊情况:1.字符串前后的空格问题;2.正负号问题;3.字符串中非1-9的字符处理;4.超出int范围的问题
三、Java代码
public class Solution {
public int myAtoi(String str) {
if(str==null||str.equals("")){
return 0;
}
boolean flag=false;
int result=0;
str=str.trim();
if(str.charAt(0)=='-'){
flag=true;
str=str.substring(1);
}else if(str.charAt(0)=='+'){
str=str.substring(1);
}
for(int i=0;i<str.length();i++){
if(str.charAt(i)<'0'||str.charAt(i)>'9')
break;
int tempstr=(int)(str.charAt(i)-'0');
int tempresult=result*10+tempstr;
// result+=((int)(str.charAt(i)-'0'))*10*str.length;
if((tempresult-tempstr)/10!=result||tempresult<0){
if(flag)
return Integer.MIN_VALUE;
else
return Integer.MAX_VALUE;
}
result=tempresult;
}
if(flag){
result*=(-1);
}
return result;
}
}
至于为什么会在判断是否超出int范围是计算tempresult<0;以四位二进制数为例,6(0110)+2(0010)=-8(1000),如果只是通过前面的(tempresult-tempstr)/10!=result来判断,-8(1000)+(-2)(1110)=6(0110),因此必须加上tempresult<0。