<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">题目:</span><span style="background-color: rgb(255, 255, 255); color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, 'Segoe UI', Arial, freesans, sans-serif; font-size: 14px; line-height: 22px;">输入一个由数字组成的字符串,把它转换成整数并输出。例如:输入字符串"123",输出整数123。</span>
要考虑的问题:
1.字符串为空串 ‘ ’ ;
2.有‘ +’或‘-’等符号;
3.非法字符;
4.字符串表示的数字过大,超出了Int 表示的范围, -2147483648 ~ 2147483647 。
public static int atoi(String s ) throws Exception{
int MAX_DIV = Integer.MAX_VALUE/10;
int MIN_DIV = -(Integer.MIN_VALUE/10);
int MAX_MOD = Integer.MAX_VALUE%10;
int MIN_MOD = -(Integer.MIN_VALUE%10);
int sum = 0,digit = 0;
int sign = 1;
int i =0;
int len = s.length();
if(len > 0 ){
//先处理正负号
digit = s.charAt(0);
if(digit == '+' || digit == '-'){
if(digit=='-'){
sign = -1;
}
if(len == 1){
throw new Exception("error");
}
i++;//处理数字部分
}
while(i < len){
digit = s.charAt(i++) - '0';
if(digit>= 0 && digit <=9){//字符符合要求
//判断是否溢出
if(sign > 0 && (sum > MAX_DIV || (sum==MAX_DIV && digit > MAX_MOD))){
throw new Exception("溢出");
}else if(sign < 0 &&(sum > MIN_DIV || (sum==MIN_DIV && digit >MIN_MOD))){
throw new Exception("溢出");
}
sum = sum*10 + digit;
}
else throw new Exception("非法字符");
}
}else{
throw new Exception("字符串长度为0");
}
return sign >0 ? sum:-sum;
}
参考: http://taop.marchtea.com/01.03.html