码迷,mamicode.com
首页 > 其他好文 > 详细

String to Integer

时间:2015-09-04 11:06:34      阅读:184      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!