aboutsummaryrefslogtreecommitdiff
path: root/exam02/rendu/ft_atoi/ft_atoi.c
blob: eda0f8d920af6d56709523fd238e03ff802fb864 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_atoi.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: exam <marvin@42.fr>                        +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2019/07/19 17:46:19 by exam              #+#    #+#             */
/*   Updated: 2019/07/19 18:03:23 by exam             ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

int	pow10(int exponent)
{
	int	acc;

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


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

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