File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
solution/008. String to Integer (atoi) Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int myAtoi (String str ) {
3
+ int len = str .length ();
4
+ if (len == 0 ) return 0 ;
5
+ char [] cs = str .toCharArray ();
6
+ int i = 0 ;
7
+ while (i < len && cs [i ] == ' ' ) i ++;
8
+ if (i ==len ) return 0 ;
9
+ char c1 = cs [i ];
10
+ int sig = 1 ;
11
+ if ((c1 > '9' || c1 < '0' )) {
12
+ if (c1 == '-' ) {
13
+ sig = -1 ;
14
+ i ++;
15
+ } else if (c1 == '+' ) {
16
+ i ++;
17
+ } else return 0 ;
18
+ }
19
+ long v = 0 ,sv = 0 ;
20
+ for (; i < len ; i ++) {
21
+ char c = cs [i ];
22
+ if (c < '0' || c > '9' ) break ;
23
+ v = v * 10 + (c - '0' );
24
+ sv = v * sig ;
25
+ if (sv > Integer .MAX_VALUE ) return Integer .MAX_VALUE ;
26
+ else if (sv < Integer .MIN_VALUE ) return Integer .MIN_VALUE ;
27
+ }
28
+ return (int ) sv ;
29
+ }
30
+ }
You can’t perform that action at this time.
0 commit comments