题解 | #把字符串转换成整数(atoi)#
把字符串转换成整数(atoi)
http://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f
import java.util.*;
import java.math.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int StrToInt (String s) {
s = s.trim();
char[] chs = s.toCharArray();
int flag = 1,i;
StringBuffer ans = new StringBuffer("");
i = 0;
if(i<chs.length&&(chs[i] == '-' || chs[i] == '+')){
if(chs[i] == '-')flag = -1;
i++;
}
while(i<chs.length&&chs[i] >= '0' && chs[i] <= '9')ans.append(chs[i++]);
if(ans.toString().equals(""))return 0;
else {
BigDecimal a = new BigDecimal(Integer.MAX_VALUE);
BigDecimal b = new BigDecimal(ans.toString());
if(a.compareTo(b)>=0){
return flag*Integer.valueOf(ans.toString());
} else {
if(flag == 1)return Integer.MAX_VALUE;
else return Integer.MIN_VALUE;
}
}
}
}