String to Integer (atoi)

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 }
原文地址:https://www.cnblogs.com/jasonC/p/3407843.html