-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatoi.c
More file actions
69 lines (61 loc) · 1.9 KB
/
Copy pathatoi.c
File metadata and controls
69 lines (61 loc) · 1.9 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gtrinida <gtrinida@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/03/11 18:16:54 by gtrinida #+# #+# */
/* Updated: 2022/03/11 18:21:01 by gtrinida ### ########.fr */
/* */
/* ************************************************************************** */
#include "minitalk.h"
static int ft_isdigit(int c)
{
return (c >= '0' && c <= '9');
}
static int ft_issign(int c)
{
return ((char)c == '-' || (char)c == '+');
}
static int ft_iswhitespace(int c)
{
return ((char)c == '\t' || (char)c == '\v' || (char)c == '\f'
|| (char)c == '\r' || (char)c == '\n' || (char)c == ' ');
}
static int ft_checkoverflow(int res, int term, int sign)
{
long long int result;
result = res;
result = (result * 10) + term;
result = result * sign;
if (result > +2147483647)
return (-1);
else if (result < -2147483648)
return (0);
return (1);
}
int ft_atoi(const char *str)
{
int i;
int res;
int sign;
i = 0;
res = 0;
sign = 1;
while (str[i] != '\0' && ft_iswhitespace(str[i]))
i++;
if (str[i] != '\0' && ft_issign(str[i]))
{
if (str[i++] == '-')
sign *= -1;
}
while (str[i] != '\0' && ft_isdigit(str[i]))
{
if (ft_checkoverflow(res, (str[i] - '0'), sign) != 1)
return (ft_checkoverflow(res, (str[i] - '0'), sign));
res = res * 10 + (str[i] - '0');
i++;
}
return (res * sign);
}