NULLs和empty strings在不同資料庫的中特點
阿新 • • 發佈:2020-09-07
題目描述:將一個字串轉換成一個整數,要求不能使用字串轉換整數的庫函式。 數值為 0 或者字串不是一個合法的數值則返回 0。
輸入描述:輸入一個字串,包括數字字母符號,可以為空。
輸出描述:如果是合法的數值表達則返回該數字,否則返回 0。
示例:
輸入:+2147483647
1a33
輸出:2147483647
0
分析:
1. 首先判斷 str 是否為空;
2.其次需要考慮到 str 是否有正負符號,這裡使用一個 boolean 變數 isNeg 表示,方便最後進行返回值的變換;
3.使用 Character.isDigit() 來判斷每個字元是否是數字;
4.考慮 int 的取值範圍,為了確保正確,使用一個 double 型的變數作為中間變數,最後強轉成 int 作為返回值;
5.判斷最後得到的中間變數是否超出 int 的取值範圍。
1 public class Solution { 2 public int StrToInt(String str) { 3 if (str.length() == 0 || "".equals(str)) { 4 return 0; 5 } 6 boolean isNeg = false; 7 if (str.charAt(0) == '+') { 8 str = str.substring(1);9 } else if (str.charAt(0) == '-') { 10 isNeg = true; 11 str = str.substring(1); 12 } 13 char[] s = str.toCharArray(); 14 double res = 0; 15 for (int i = 0; i < s.length; i++) { 16 if (!Character.isDigit(s[i])) { 17 return0; 18 } else { 19 res += Math.pow(10, s.length - i - 1) * (s[i] - 48); 20 } 21 } 22 if(isNeg==false) { 23 if(res>Integer.MAX_VALUE) { 24 return 0; 25 }else { 26 return (int)res; 27 } 28 }else { 29 if((0-res)<Integer.MIN_VALUE) { 30 return 0; 31 }else { 32 return (int)(0-res); 33 } 34 } 35 } 36 }