-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0008-string-to-integer-atoi.c
More file actions
50 lines (43 loc) · 1.01 KB
/
0008-string-to-integer-atoi.c
File metadata and controls
50 lines (43 loc) · 1.01 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
8. String to Integer (atoi)
Submitted: March 19, 2026
Runtime: 0 ms (beats 100.00%)
Memory: 9.31 MB (beats 35.57%)
*/
static inline long long llmin(long long a, long long b) {
return a < b ? a : b;
}
static inline long long llmax(long long a, long long b) {
return a > b ? a : b;
}
bool out_of_range(long long x) {
return x >= 2147483647LL || x <= -2147483648LL;
}
int make_in_range(long long x) {
return llmax(-2147483648LL, llmin(x, 2147483647LL));
}
int myAtoi(char* s) {
const char* p = s;
while (*p == ' ') {
++p;
}
long long res = 0;
bool negative = false;
if (*p == '-') {
negative = true;
++p;
} else if (*p == '+') {
negative = false;
++p;
}
while (*p && '0' <= *p && *p <= '9') {
printf("%d\n", res);
res *= 10;
res += *p - '0';
++p;
if (out_of_range(negative ? -res : res)) {
return make_in_range(negative ? -res : res);
}
}
return negative ? -res : res;
}