标签:
1 public class Solution { 2 public int myAtoi(String str) { 3 if(str == null || str.length() ==0 ) return 0; 4 str = str.trim(); 5 boolean isPositive = true; 6 boolean isOverFloew = false; 7 long res = 0; 8 for(int i = 0 ; i < str.length(); i++) 9 { 10 char ch = str.charAt(i); 11 if(i ==0 && (ch == ‘-‘ || ch == ‘+‘)) 12 { 13 if(ch == ‘-‘) 14 { 15 isPositive = false; 16 } 17 continue; 18 } 19 if(ch > ‘9‘ || ch < ‘0‘) break;//"+-2" " -0012a42" 20 res = res * 10 + (ch - ‘0‘); 21 if( res > Integer.MAX_VALUE) 22 isOverFloew = true; 23 } 24 res = isPositive == true ? res : -res; 25 26 if( isOverFloew == true && isPositive == true ) 27 return Integer.MAX_VALUE; 28 else if(isOverFloew == true && isPositive == false ) 29 return Integer.MIN_VALUE; 30 else 31 return (int) res; 32 } 33 }
标签:
原文地址:http://www.cnblogs.com/sweetculiji/p/4781307.html