字符串转化为整数
題目:
字符串轉換為整數 : atoi
可能的輸入:
1 帶符號數
2 無符號數
3 零
4 空指針
5 超出表示范圍 – 暫時僅僅是直接退出且設置最小 – 可以考慮此時拋個異常
6 非法輸入,比如并不是一個0-9或者+ -組成的字符串 – 對于非法輸入一律返回的是Integer.MIN_VALUE
?
解答:
1 public class Solution { 2 3 public static long strToInt(String str) { 4 if(str == null) { 5 return Long.MIN_VALUE; 6 } 7 8 if(str.length() == 0) { 9 return 0; 10 } 11 12 for(int i = 0; i < str.length(); i++) { 13 if(!judge(str.charAt(i))) { 14 return Long.MIN_VALUE; 15 } 16 } 17 18 char[] chars = str.toCharArray(); 19 long result = 0; 20 21 if(char[0] == '+' || char[0] == '-') { 22 result = trans(str.substring(1)); 23 } else { 24 result = trans(str); 25 } 26 27 if(result > 0 && char[0] == '-') { 28 result = -result; 29 } 30 31 return result; 32 } 33 34 public static boolean judge(char c) { 35 if(c == '+' || c == '-' || (c >= '0' && c <= '9')) { 36 return true; 37 } else { 38 return false; 39 } 40 } 41 42 private static long trans(String str) { 43 if(str.length() == 0) { 44 return 0; 45 } 46 47 long result = 0; 48 for(int i = 0; i < str.length(); i++) { 49 result = result*10 + str.charAt(i)-'0'; 50 51 // important here 52 if(result > Long.MAX_VALUE) { 53 result = Long.MAX_VALUE; 54 break; 55 } 56 } 57 58 return result; 59 } 60 }?
轉載于:https://www.cnblogs.com/wylwyl/p/10477256.html
總結
- 上一篇: 并不对劲的长链剖分
- 下一篇: Django之ORM(多对多)