aboutsummaryrefslogtreecommitdiff
path: root/c04/ex03/ft_atoi.c
blob: a26308e2eb72b778fce045622ebec3fe0d806504 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_atoi.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <charles.cabergs@gmail.com>       +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2019/07/06 07:31:38 by cacharle          #+#    #+#             */
/*   Updated: 2019/07/06 15:48:43 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

int	pow10(int exponent)
{
	int	accumulator;

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

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

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