將一個字串轉換成一個整數,要求不能使用字串轉換整數的庫函式, 數值為 0 或者字串不是一個合法的數值則回傳 0
解題思路
字符 ‘0’ 的 ASCII 值是 48,‘1’ 到 '9' 則是從 48 起始依次遞增,因此解題的關鍵在于:
- 判斷有沒有 '+'、'-' 等符號位,如果沒有符號位默認為正整數
- 依次取字串中的每一個字符,判斷是否在 '1' 到 '9' 的范圍之內
public class Solution {
public int StrToInt(String str) {
if(str == null || str.length() == 0) {
return 0;
} else if(str.length() == 1 && (str.charAt(0) == '+' || str.charAt(0) == '-')) {
return 0;
}
int result = 0;
boolean flag = true;
int j = 1;
if(str.charAt(0) == '+') {
str = str.substring(1, str.length());
}
if(str.charAt(0) == '-') {
flag = false;
str = str.substring(1, str.length());
}
for(int i = str.length() - 1; i >= 0; i--) {
int temp = str.charAt(i) - 48;
if(temp < 0 || temp > 9) {
return 0;
}
result += temp * j;
j *= 10;
}
if(flag == false) {
return -result;
}
return result;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/211025.html
標籤:其他
上一篇:容器(四)容器常用操作【20】
下一篇:DC-4靶機
