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 @@ -379,33 +379,28 @@ class Solution {
379379``` C
380380int myAtoi (char* s) {
381381 int i = 0;
382- int sign = 1;
383- long result = 0;
382+
384383 while (s[i] == ' ') {
385384 i++;
386385 }
386+
387+ int sign = 1;
387388 if (s[i] == '-' || s[i] == '+') {
388389 sign = (s[i] == '-') ? -1 : 1;
389390 i++;
390391 }
392+
393+ int res = 0;
391394 while (isdigit(s[i])) {
392- result = result * 10 + (s[ i] - '0');
393- if (sign == 1 && result > INT_MAX) {
394- return INT_MAX;
395- }
396- if (sign == -1 && -result < INT_MIN) {
397- return INT_MIN;
395+ int digit = s[i] - '0';
396+ if (res > INT_MAX / 10 || (res == INT_MAX / 10 && digit > INT_MAX % 10)) {
397+ return sign == 1 ? INT_MAX : INT_MIN;
398398 }
399+ res = res * 10 + digit;
399400 i++;
400401 }
401- b
402- result
403- * = sign;
404- if (result > INT_MAX)
405- return INT_MAX;
406- if (result < INT_MIN)
407- return INT_MIN;
408- return (int) result;
402+
403+ return res * sign;
409404}
410405```
411406
You can’t perform that action at this time.
0 commit comments