-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatoi.c
More file actions
27 lines (24 loc) · 645 Bytes
/
atoi.c
File metadata and controls
27 lines (24 loc) · 645 Bytes
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
int myAtoi(char* s) {
int sign = 1, base = 0, i = 0;
// if whitespaces then ignore.
while (s[i] == ' ') {
i++;
}
// sign of number
if (s[i] == '-' || s[i] == '+') {
sign = 1 - 2 * (s[i++] == '-');
}
// checking for valid input
while (s[i] >= '0' && s[i] <= '9') {
// handling overflow test case
if (base > INT_MAX / 10
|| (base == INT_MAX / 10 && s[i] - '0' > 7)) {
if (sign == 1)
return INT_MAX;
else
return INT_MIN;
}
base = 10 * base + (s[i++] - '0');
}
return base * sign;
}