|
2 | 2 |
|
3 | 3 | publicclass_8 { |
4 | 4 |
|
5 | | -publicstaticclassSolution1 { |
6 | | -/** |
7 | | - * four corner cases: |
8 | | - * 1. discards all leading zeroes |
9 | | - * 2. sign of the number |
10 | | - * 3. overflow |
11 | | - * 4. invalid input |
12 | | - * */ |
13 | | -publicintmyAtoi(Stringstr) { |
14 | | -intpointer =0; |
15 | | -intresult =0; |
16 | | -while (pointer <str.length() &&Character.isWhitespace(str.charAt(pointer))) { |
17 | | -pointer++; |
18 | | -} |
19 | | -if (pointer ==str.length()) { |
20 | | -return0; |
21 | | -} |
22 | | -booleannegativeFlag = (str.charAt(pointer) =='-'); |
23 | | -if (str.charAt(pointer) =='+' ||str.charAt(pointer) =='-') { |
24 | | -pointer++; |
25 | | -} |
26 | | -for (;pointer <str.length();pointer++) { |
27 | | -if (str.charAt(pointer) >'9' ||str.charAt(pointer) <'0') { |
28 | | -break; |
29 | | -}else { |
30 | | -intdigit =str.charAt(pointer) -'0'; |
31 | | -if (!negativeFlag &&result > (Integer.MAX_VALUE -digit) /10) { |
32 | | -returnInteger.MAX_VALUE; |
33 | | -}elseif (negativeFlag &&result < (Integer.MIN_VALUE +digit) /10) { |
34 | | -returnInteger.MIN_VALUE; |
35 | | -} |
36 | | -result =result *10 + (negativeFlag ? -digit :digit); |
37 | | -} |
38 | | -} |
39 | | -returnresult; |
40 | | -} |
41 | | -} |
| 5 | +publicstaticclassSolution1 { |
| 6 | +/** |
| 7 | + * four corner cases: |
| 8 | + * 1. discards all leading zeroes |
| 9 | + * 2. sign of the number |
| 10 | + * 3. overflow |
| 11 | + * 4. invalid input |
| 12 | + */ |
| 13 | +publicintmyAtoi(Strings) { |
| 14 | +intpointer =0; |
| 15 | +intresult =0; |
| 16 | +while (pointer <s.length() &&Character.isWhitespace(s.charAt(pointer))) { |
| 17 | +pointer++; |
| 18 | +} |
| 19 | +if (pointer ==s.length()) { |
| 20 | +return0; |
| 21 | +} |
| 22 | +booleannegativeFlag = (s.charAt(pointer) =='-'); |
| 23 | +if (s.charAt(pointer) =='+' ||s.charAt(pointer) =='-') { |
| 24 | +pointer++; |
| 25 | +} |
| 26 | +for (;pointer <s.length();pointer++) { |
| 27 | +if (s.charAt(pointer) >'9' ||s.charAt(pointer) <'0') { |
| 28 | +break; |
| 29 | +}else { |
| 30 | +intdigit =s.charAt(pointer) -'0'; |
| 31 | +if (!negativeFlag &&result > (Integer.MAX_VALUE -digit) /10) { |
| 32 | +returnInteger.MAX_VALUE; |
| 33 | +}elseif (negativeFlag &&result < (Integer.MIN_VALUE +digit) /10) { |
| 34 | +returnInteger.MIN_VALUE; |
| 35 | +} |
| 36 | +result =result *10 + (negativeFlag ? -digit :digit); |
| 37 | +} |
| 38 | +} |
| 39 | +returnresult; |
| 40 | +} |
| 41 | +} |
42 | 42 |
|
43 | 43 | } |