JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1.trim

2.符号

3.overflow

 1 public class Solution {
 2     public int atoi(String str) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         if(str == null)
 6             return 0;
 7         if(str.length() == 0)
 8             return 0;
 9         str = str.trim();
10         boolean positive = true;
11         long result = 0;
12         if(str.charAt(0) == '-')
13         {
14             str = str.substring(1);
15             positive = false;
16         }
17         else if(str.charAt(0) == '+')
18         {
19             str = str.substring(1);
20         }
21         for(int i=0;i<str.length();i++)
22         {
23             char tmp = str.charAt(i);
24             if(tmp >= '0' && tmp <= '9')
25                 result = 10 * result + tmp - '0';
26             else
27                 break;
28         }
29         if(result > Integer.MAX_VALUE)
30             return positive?Integer.MAX_VALUE:Integer.MIN_VALUE;
31         return positive?(int)result:(int)(-1*result);
32     }
33 }

 

posted on 2013-11-05 08:18  JasonChang  阅读(210)  评论(0编辑  收藏  举报