File tree Expand file tree Collapse file tree 1 file changed +11
-16
lines changed
solution/0000-0099/0008.String to Integer (atoi) Expand file tree Collapse file tree 1 file changed +11
-16
lines changed Original file line number Diff line number Diff line change @@ -391,33 +391,28 @@ class Solution {
391391``` C
392392int myAtoi (char* s) {
393393 int i = 0;
394- int sign = 1;
395- long result = 0;
394+
396395 while (s[i] == ' ') {
397396 i++;
398397 }
398+
399+ int sign = 1;
399400 if (s[i] == '-' || s[i] == '+') {
400401 sign = (s[i] == '-') ? -1 : 1;
401402 i++;
402403 }
404+
405+ int res = 0;
403406 while (isdigit(s[i])) {
404- result = result * 10 + (s[ i] - '0');
405- if (sign == 1 && result > INT_MAX) {
406- return INT_MAX;
407- }
408- if (sign == -1 && -result < INT_MIN) {
409- return INT_MIN;
407+ int digit = s[i] - '0';
408+ if (res > INT_MAX / 10 || (res == INT_MAX / 10 && digit > INT_MAX % 10)) {
409+ return sign == 1 ? INT_MAX : INT_MIN;
410410 }
411+ res = res * 10 + digit;
411412 i++;
412413 }
413- b
414- result
415- * = sign;
416- if (result > INT_MAX)
417- return INT_MAX;
418- if (result < INT_MIN)
419- return INT_MIN;
420- return (int) result;
414+
415+ return res * sign;
421416}
422417```
423418
You can’t perform that action at this time.
0 commit comments