LeetCode ---8. String to Integer (atoi)

 1 public int myAtoi(String str) {
 2         long value = 0;
 3         char sign = '\0';
 4         //是否已经存在非零值,存在true,不存在false
 5         boolean existNonzero = false;
 6         boolean over = false;
 7         char ch;
 8         
 9         for(int i = 0; !over && i < str.length(); i++) {
10             ch = str.charAt(i);
11             if(ch == ' ' || ch == '.' || ch == '+' || ch == '-' || (ch <= '9' && ch >= '0')) {
12                 switch(ch) {
13                     case '+' :
14                     case '-' :
15                         if(existNonzero) {
16                             over = true;
17                         } else if(sign == '\0') {
18                             sign = (ch == '-') ? '-' : '+';
19                             existNonzero = true;
20                         }
21                         break;
22                     case ' ' :
23                         over = existNonzero;
24                         break;
25                     case '0' :
26                         if(existNonzero) {
27                             value *= 10;                            
28                         }
29                         break;
30                     default :
31                         value = (value >= 0) ? (value * 10 + ch - 48) : (value * 10 - ch + 48);
32                         existNonzero = true;
33                         break;
34                 }
35             } else break;
36             if(sign == '-' && value > 0) {
37                 value = -value;
38             }
39             if(value > Integer.MAX_VALUE) {
40                 return Integer.MAX_VALUE;
41             }
42             if(value < Integer.MIN_VALUE) {
43                 return Integer.MIN_VALUE;
44             }
45         }
46         return (int) value; 
47     }

 

posted @ 2017-05-17 22:04  zouxiaochuan  阅读(165)  评论(0)    收藏  举报