将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
这题我不会,想到用字符减‘0’,但其实这题在于处理边界。转载答案中一个回答,
- 捕捉异常
这种严格上不符合要求,直接转化了,但是捕捉异常的思路很好
public int StrToInt(String str) {
Integer res=0;
try {
res = new Integer(str);
} catch (NumberFormatException e) {
} finally {
return res;
}
}
public int StrToInt(String str) {
//最优解
if(str == null || "".equals(str.trim()))return 0;
str = str.trim();
char[] arr = str.toCharArray();
int i = 0;
int flag = 1;
int res = 0;
if(arr[i] == '-'){
flag = -1;
}
if( arr[i] == '+' || arr[i] == '-'){
i++;
}
while(i<arr.length ){
//是数字
if(isNum(arr[i])){
int cur = arr[i] - '0';
if(flag == 1 && (res > Integer.MAX_VALUE/10 || res == Integer.MAX_VALUE/10 && cur >7)){
return 0;
}
if(flag == -1 && (res > Integer.MAX_VALUE/10 || res == Integer.MAX_VALUE/10 && cur >8)){
return 0;
}
res = res*10 +cur;
i++;
}else{
//不是数字
return 0;
}
}
return res*flag;
}
public static boolean isNum(char c){
return c>='0'&& c<='9';
}