|
13 | 13 | public class String2Integer { |
14 | 14 |
|
15 | 15 | public int myAtoi(String str) { |
16 | | - long n = 0; |
17 | | - |
18 | | - str = str.trim(); |
19 | | - |
20 | | - // 这里要防御空串 |
21 | | - if (str.length() == 0) { |
22 | | - return 0; |
23 | | - } |
24 | | - |
25 | | - int sign = 1; |
26 | | - |
27 | | - switch (str.charAt(0)) { |
28 | | - case '-': |
| 16 | + int i = 0, sign = 1; |
| 17 | + for ( ; i < str.length() && str.charAt(i) == ' '; i++); |
| 18 | + if (i < str.length()) { |
| 19 | + char csign = str.charAt(i); |
| 20 | + if (csign == '-') { |
29 | 21 | sign = -1; |
30 | | - case '+': |
31 | | - str = str.substring(1); |
32 | | - break; |
| 22 | + i++; |
| 23 | + } else if (csign == '+') { |
| 24 | + sign = 1; |
| 25 | + i++; |
| 26 | + } else if (csign < '0' || csign > '9') { |
| 27 | + return 0; |
| 28 | + } else {} |
33 | 29 | } |
34 | | - |
35 | | - for (char c : str.toCharArray()) { |
36 | | - if (c >= '0' && c <= '9') { |
37 | | - n = n * 10 + (c - '0'); |
38 | | - |
39 | | - if (n * sign > Integer.MAX_VALUE) { |
40 | | - return Integer.MAX_VALUE; |
41 | | - } else if (n * sign < Integer.MIN_VALUE) { |
42 | | - return Integer.MIN_VALUE; |
43 | | - } |
44 | | - |
45 | | - } else { |
| 30 | + long number = 0; |
| 31 | + for ( ; i < str.length(); i++) { |
| 32 | + char c = str.charAt(i); |
| 33 | + if (c < '0' || c > '9') { |
46 | 34 | break; |
47 | 35 | } |
48 | | - } |
| 36 | + number = number * 10 + (c - '0'); |
49 | 37 |
|
50 | | - return (int) (n * sign); |
| 38 | + if (number * sign > Integer.MAX_VALUE) { |
| 39 | + return Integer.MAX_VALUE; |
| 40 | + } |
| 41 | + if (number * sign < Integer.MIN_VALUE) { |
| 42 | + return Integer.MIN_VALUE; |
| 43 | + } |
| 44 | + } |
| 45 | + return (int) (number * sign); |
51 | 46 | } |
52 | 47 | } |
0 commit comments