题目
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
分析
思路一:
思路见注释,注意需要判断越界情况
代码:
public class Solution {
public int StrToInt(String str) {
if(str == null || str.length() == 0) return 0;
int i = 0;//指示字符索引,从第一个字符开始
boolean negative = false;//表示符号,默认为正
int res = 0;//返回的整数
int limit = -Integer.MAX_VALUE;//范围,正数和负数在返回前都表示为负数,最后根据neagtive变为正数或者负数
if(str.charAt(i) < '0') {//如果第一个字符不是数字,那就只能是'+'/’-‘,其他情况都为0
if(str.charAt(i) == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if(str.charAt(i) != '+') {//为其他不合法的字符
return 0;
}
if(str.length() == 1) return 0;//只有符号,返回0
i++;//进行下一位判断
}
int digit = 0;//字符转换后的数字
while(i < str.length()) {
if(str.charAt(i) > '0' && str.charAt(i) < '9') {
digit = str.charAt(i++) - '0';
if((res * 10) < limit) return 0;//再往后移位前需要判断溢出情况
res *= 10;
if((res - digit) < limit) return 0;
res -= digit;
} else {
return 0;
}
}
return negative ? res : -res;
}
}