File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
main/java/s0008.string.to.integer.atoi
test/java/s0008.string.to.integer.atoi Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ package s0008 .string .to .integer .atoi ;
2+
3+ public class Solution {
4+ public int myAtoi (String str ) {
5+ if (str == null || str .length () == 0 )
6+ return 0 ;
7+
8+ int i = 0 ;
9+ boolean negetiveSign = false ;
10+ char [] input = str .toCharArray ();
11+
12+ while (i < input .length && input [i ] == ' ' ) {
13+ i ++;
14+ }
15+
16+ if (i == input .length ) {
17+ return 0 ;
18+ } else if (input [i ] == '+' ) {
19+ i ++;
20+ } else if (input [i ] == '-' ) {
21+ i ++;
22+ negetiveSign = true ;
23+ }
24+
25+ int num = 0 ;
26+ while (i < input .length && input [i ] <= '9' && input [i ] >= '0' ) {
27+ int tem = input [i ] - '0' ; //current char
28+ tem = negetiveSign ? -tem : tem ;
29+
30+ if (num == 0 && tem == '0' ) { // avoid invalid number like 038
31+ i ++;
32+ } else if (num == Integer .MIN_VALUE / 10 && tem <= -8 || num < Integer .MIN_VALUE / 10 ) {
33+ return Integer .MIN_VALUE ;
34+ } else if (num == Integer .MAX_VALUE / 10 && tem >= 7 || num > Integer .MAX_VALUE / 10 ) {
35+ return Integer .MAX_VALUE ;
36+ } else {
37+ num = num * 10 + tem ;
38+ i ++;
39+ }
40+ }
41+ return num ;
42+ }
43+ }
Original file line number Diff line number Diff line change 1+ package s0008 .string .to .integer .atoi ;
2+
3+ import static org .hamcrest .CoreMatchers .equalTo ;
4+ import static org .hamcrest .MatcherAssert .assertThat ;
5+ import org .junit .Test ;
6+
7+ public class SolutionTest {
8+ @ Test
9+ public void myAtoi () {
10+ assertThat (new Solution ().myAtoi ("42" ), equalTo (42 ));
11+ }
12+ }
You can’t perform that action at this time.
0 commit comments