首页 > 其他 > 详细

String to Integer

时间:2015-09-04 11:05:50      阅读:251      评论:0      收藏: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 }

 

String to Integer

原文:http://www.cnblogs.com/sweetculiji/p/4781307.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!