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.
代码如下:
public class StringToInteger {
public int myAtoI(String str){
int index=0,sign=1,result=0;
//1、空字符串
if(str.length() == 0)
return 0;
//2、删除字符前面的空格
while(str.charAt(index) == ' ' && index < str.length()){
index++;
}
//3、正负号
if(str.charAt(index) == '+' || str.charAt(index) == '-'){
sign = str.charAt(index)=='+' ? 1 : -1;
index++;
}
//4、转换
while(index < str.length()){
int digit = str.charAt(index) - '0';
if( digit<0 || digit>9 ) break;
//避免溢出
if(Integer.MAX_VALUE/10 < result || Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE%10 < digit)
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
result = result * 10 + digit;
index++;
}
return result*sign;
}
}
也可先转为字符数组再进行转换。