題目描述
將一個字符串轉換成一個整數,要求不能使用字符串轉換整數的庫函數。 數值爲0或者字符串不是一個合法的數值則返回0
輸入描述:
輸入一個字符串,包括數字字母符號,可以爲空
輸出描述:
如果是合法的數值表達則返回該數字,否則返回0
思路
1 判斷字符串是否爲空,如果爲空直接返回0
2 由於可以輸入符號,故需特殊處理字符串
3 由於整數最小值的絕對值 > 最大值的絕對值,故需處理整數邊界問題
4 正負有異,巧妙點在於將布爾思想轉換爲數字思想,讓符號位參與運算
代碼
//字符串處理代碼
public static int StrToInt(String str){
int result = 0;
if(str instanceof String && str != null){
String temp = str.trim(); //去除字符串前後空白字符串
char[] chars = temp.toCharArray(); //將字符串轉換成數組
if (chars.length > 0) {
if (chars[0] == '+') { //可能是帶符號的字符數字
result = StrToInt1(chars, 1, 1);
} else if (chars[0] == '-') {
result = StrToInt1(chars, 1, -1);
} else if (chars[0] >= '0' && chars[0] <= '9') { //無符號的字符數字
result = StrToInt1(chars, 0, 1);
}
}
return result;
}
return 0;
}
//實際轉換代碼
public static int StrToInt1(char[] chars, int begin, int isNegtive){
long result = 0; //如果是int類型就需要利用INT_MAX/10去判定,所以使用long類型
for(; begin < chars.length; begin++){
if(chars[begin] >= '0' && chars[begin] <= '9'){
result = result*10 + (chars[begin]-'0')*isNegtive;
}else{
result = 0;
break;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
result = 0;
}
}
return (int)result;
}
測試用例
String str = " -2147483649 ";
String str = " -2147483647 ";
String str = " 2147483648";
String str = " 2147483646";
String str = " +123 ";
String str = " -6 ";
String str = " 1a32 ";
String str = " 1 32 ";
測試結果
0
-2147483647
0
2147483646
123
-6
0
0