File tree Expand file tree Collapse file tree 1 file changed +12
-17
lines changed
solution/0000-0099/0008.String to Integer (atoi) Expand file tree Collapse file tree 1 file changed +12
-17
lines changed Original file line number Diff line number Diff line change 11int myAtoi (char * s ) {
22 int i = 0 ;
3- int sign = 1 ;
4- long result = 0 ;
3+
54 while (s [i ] == ' ' ) {
65 i ++ ;
76 }
7+
8+ int sign = 1 ;
89 if (s [i ] == '-' || s [i ] == '+' ) {
910 sign = (s [i ] == '-' ) ? -1 : 1 ;
1011 i ++ ;
1112 }
13+
14+ int res = 0 ;
1215 while (isdigit (s [i ])) {
13- result = result * 10 + (s [i ] - '0' );
14- if (sign == 1 && result > INT_MAX ) {
15- return INT_MAX ;
16- }
17- if (sign == -1 && - result < INT_MIN ) {
18- return INT_MIN ;
16+ int digit = s [i ] - '0' ;
17+ if (res > INT_MAX / 10 || (res == INT_MAX / 10 && digit > INT_MAX % 10 )) {
18+ return sign == 1 ? INT_MAX : INT_MIN ;
1919 }
20+ res = res * 10 + digit ;
2021 i ++ ;
2122 }
22- b
23- result
24- *= sign ;
25- if (result > INT_MAX )
26- return INT_MAX ;
27- if (result < INT_MIN )
28- return INT_MIN ;
29- return (int ) result ;
30- }
23+
24+ return res * sign ;
25+ }
You can’t perform that action at this time.
0 commit comments