-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_atoi.c
37 lines (27 loc) · 778 Bytes
/
_atoi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// https://leetcode.com/problems/string-to-integer-atoi/description/
#include <ctype.h>
#include <limits.h>
int myAtoi(register char* str) {
// Skip whitespaces
while(isspace(*str)) str++;
// Decide sign
int pos = 1;
switch(*str) {
case '-': pos = 0; ++str; break;
case '+': ++str; break;
}
// Accumulator
register int acc = 0;
// Char to digit
register int chr;
// Parse digits
while(isdigit(*str)) {
chr = (int)(*str % '0');
// Check for overflow
if(acc > (INT_MAX/10) || (acc == (INT_MAX/10) && chr > INT_MAX%10))
return pos ? INT_MAX : INT_MIN;
// Increment accumulator
acc = acc*10 + chr; str++;
}
return pos ? acc : -acc;
}