aboutsummaryrefslogtreecommitdiff
path: root/exam00/cacharle/ft_atoi/ft_atoi.c
blob: 81f07067355e5d92e89933b044bde706f4b346a6 (plain)
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
char	ctoi(char c)
{
	return (c - '0');
}

int		ft_strlen(const char *str)
{
	int	counter;

	counter = 0;
	while (*str >= '0' && *str <= '9')
	{
		counter++;
		str++;
	}
	return (counter);
}

int		pow10(int exponent)
{
	int	accumulator;

	accumulator = 1;
	while (exponent > 0)
	{
		accumulator *= 10;
		exponent--;
	}
	return (accumulator);
}

int		ft_atoi(const char *str)
{
	int	nb;
	int	i;
	int	is_negative;

	while (*str == ' ' || *str == '\t'|| *str == '\n'
		   || *str == '\v'|| *str == '\f'|| *str == '\r')
		str++;
	if (*str == '-')
		is_negative = 1;
	else
		is_negative = 0;
	if (*str == '-' || *str == '+')
	{
		str++;
	}
	nb = 0;
	i = ft_strlen(str) - 1;
	while (*str >= '0' && *str <= '9')
	{
		nb += pow10(i) * ctoi(*str);
		i--;
		str++;
	}
	if (is_negative)
		nb = -nb;
	return (nb);
}