標籤:style blog http color os io strong for
String to Integer (atoi)
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
演算法思路:
坑比較多,沒難度。開整之前建議先把str預先處理一下
【注意】邊界case:
全空格、全非法字元、空串<-這三種預先處理之後都變成空串了。
溢出。因此先把result聲明成long型。
符號處理:
兩個boolean變數表示加號或減號,但是一旦有了某個符號,第二個符號就變成非法字元了。字串中未出現符號,按照正號處理。
代碼如下:
1 public class Solution { 2 public int atoi(String str) { 3 if(str == null || str.trim().length() == 0) return 0; 4 str = str.trim(); 5 StringBuilder sb = new StringBuilder(); 6 int length = str.length(); 7 ////preprocess,only maintain num and operater 8 for(int i = 0; i < length; i++){ 9 if(str.charAt(i) == ‘+‘ || str.charAt(i) == ‘-‘ || (str.charAt(i) <= ‘9‘ && str.charAt(i) >= ‘0‘)){10 sb.append(str.charAt(i));11 }else break;12 }13 length = sb.length();14 boolean positive = false,negative = false;15 long res = 0;16 for(int i = 0; i < length; i++){17 //the second time appearrance of operater is invalide18 if((sb.charAt(i) == ‘+‘ || sb.charAt(i) == ‘-‘) && (positive || negative)) 19 break;20 if(sb.charAt(i) == ‘+‘){21 positive = true;22 }else if(sb.charAt(i) == ‘-‘){23 negative = true;24 }else{25 res = res * 10 + (sb.charAt(i) - ‘0‘);26 }27 }28 if(!positive && !negative) positive = true;29 // process overflow situation30 if(positive) return res > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) res;31 return res > Integer.MAX_VALUE ? Integer.MIN_VALUE : (int)res * -1; 32 }33 }