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 {
391
391
``` C
392
392
int myAtoi (char* s) {
393
393
int i = 0;
394
- int sign = 1;
395
- long result = 0;
394
+
396
395
while (s[i] == ' ') {
397
396
i++;
398
397
}
398
+
399
+ int sign = 1;
399
400
if (s[i] == '-' || s[i] == '+') {
400
401
sign = (s[i] == '-') ? -1 : 1;
401
402
i++;
402
403
}
404
+
405
+ int res = 0;
403
406
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;
410
410
}
411
+ res = res * 10 + digit;
411
412
i++;
412
413
}
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;
421
416
}
422
417
```
423
418
You can’t perform that action at this time.
0 commit comments