File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ package array ;
2
+
3
+ /**
4
+ * @author liangqian0723@gmail.com
5
+ * @since 2020/4/3 6:58 AM
6
+ */
7
+ public class LC_8_StringToIntegerAtoi {
8
+ public int myAtoi (String str ) {
9
+ if (null == str || str .length () == 0 ) return 0 ;
10
+ char [] array = str .toCharArray ();
11
+ int res = 0 ;
12
+ int curIndex = 0 ;
13
+ int flag = 1 ;
14
+ while (array [curIndex ] == ' ' ) {
15
+ curIndex ++;
16
+ if (curIndex >= str .length ()) return 0 ;
17
+ }
18
+ if (array [curIndex ] == '-' ) flag = -1 ;
19
+ if (array [curIndex ] == '+' || array [curIndex ] == '-' ) curIndex ++;
20
+ while (curIndex < str .length () && Character .isDigit (array [curIndex ])) {
21
+ int r = array [curIndex ] - '0' ;
22
+ if (res > (Integer .MAX_VALUE - r ) / 10 || res < Integer .MIN_VALUE / 10 ) {
23
+ return flag > 0 ? Integer .MAX_VALUE : Integer .MIN_VALUE ;
24
+ }
25
+ res = res * 10 + r ;
26
+ curIndex ++;
27
+ }
28
+ return flag > 0 ? res : res * flag ;
29
+ }
30
+ }
Original file line number Diff line number Diff line change
1
+ package array ;
2
+
3
+ import org .junit .Test ;
4
+
5
+ import static org .hamcrest .core .Is .is ;
6
+ import static org .junit .Assert .assertThat ;
7
+
8
+ /**
9
+ * @author liangqian0723@gmail.com
10
+ * @since 2020/4/3 6:56 AM
11
+ */
12
+ public class LC_8_StringToIntegerAtoiTest {
13
+ @ Test
14
+ public void test_string_to_integer_atomic () {
15
+ LC_8_StringToIntegerAtoi at = new LC_8_StringToIntegerAtoi ();
16
+ assertThat (at .myAtoi (" -42" ), is (-42 ));
17
+ assertThat (at .myAtoi ("4193 with words" ), is (4193 ));
18
+ assertThat (at .myAtoi ("words and 987" ), is (0 ));
19
+ assertThat (at .myAtoi (" " ), is (0 ));
20
+ assertThat (at .myAtoi ("2147483648" ), is (2147483647 ));
21
+ }
22
+ }
You can’t perform that action at this time.
0 commit comments