算法-String转int
2020-07-28 本文已影响0人
zzq_nene
在实现String转int的时候,需要考虑字符串中是否有字符是非数字字符,第一个字符是否是符号字符,比如负号或者正号等。
数字字符的范围是48-57,即0-9
而负号字符的ASCII码的值为45
public static int strToInt(String str) {
if (str == null || str.length() == 0) {
return 0;
}
int result = 0;
char[] chars = str.toCharArray();
int len = chars.length;
for (int i = len - 1, j = 0; i > 0; i--, j++) {
// 从尾巴开始取字符
int c = (int)chars[i];
// 说明字符串中存在非数字字符
if (c < 48 || c > 57) {
return 0;
} else {
// Math.pow返回10的j次幂值
result += (c - 48) * Math.pow(10, j);
}
}
// 有可能c是带有符号的,所以需要把第一个字符单独判断
// 如果第一个字符并不是负号,并且是数字字符,那么就需要按当前数字乘以10的length-1次幂
int c = (int)chars[0];
if (c <= 57 && c >= 48) {
result += (c - 48) * Math.pow(10, len - 1);
}
if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
return 0;
} else if (str.equals("2147483648")) {
// 其实这里2147483648已经是大于int的最大值
if (c == 45) {
result = -2147483648;
}
} else if (str.equals("-2147483648")) {
result = -2147483648;
} else {
if (c == 45) {
result = -result;
}
}
return result;
}