糖醋里脊

有召唤,爱自由.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

String to Integer

Posted on 2015-09-04 10:16  糖醋里脊er  阅读(200)  评论(0)    收藏  举报
注意所有的有可能输入。
判断正负数。
是否溢出。
 
 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 }