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 {
379
379
``` C
380
380
int myAtoi (char* s) {
381
381
int i = 0;
382
- int sign = 1;
383
- long result = 0;
382
+
384
383
while (s[i] == ' ') {
385
384
i++;
386
385
}
386
+
387
+ int sign = 1;
387
388
if (s[i] == '-' || s[i] == '+') {
388
389
sign = (s[i] == '-') ? -1 : 1;
389
390
i++;
390
391
}
392
+
393
+ int res = 0;
391
394
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;
398
398
}
399
+ res = res * 10 + digit;
399
400
i++;
400
401
}
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;
409
404
}
410
405
```
411
406
You can’t perform that action at this time.
0 commit comments