summaryrefslogtreecommitdiff
path: root/ft_itoa.c
blob: f892fb184da019bfc7554d53366cd88ca664f388 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
Libft Copyright (C) 2026 yctct

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#include "libft.h"

static long int	ft_nbrlen(long int n)
{
	int	len;

	len = 0;
	if (n < 0)
	{
		n = -n;
		len += 1;
	}
	while (n)
	{
		n /= 10;
		len++;
	}
	return (len);
}

char	*ft_itoa(int nb)
{
	char	*c;
	int		len;
	long	n;

	n = nb;
	if (n == 0)
		return (ft_strdup("0"));
	len = ft_nbrlen(n);
	c = malloc(sizeof(char) * (len + 1));
	if (!c)
		return (NULL);
	if (n < 0)
	{
		n = -n;
		c[0] = '-';
	}
	c[len] = '\0';
	while (n)
	{
		c[--len] = (n % 10) + '0';
		n /= 10;
	}
	return (c);
}
/*
#include <stdio.h>
#include <stdlib.h>

int	main(void)
{
	int		n1;
	int		n2;
	int		n3;
	int		n4;
	int		n5;
	char	*ptr;
	char	*ptr2;
	char	*ptr3;
	char	*ptr4;
	char	*ptr5;
	char	*ptr6;
	char	c;

	c = 'a';
	n1 = 42;
	n2 = 0;
	n3 = -42;
	n4 = 2147483647;
	n5 = -2147483648;
	ptr = ft_itoa(n1);
	printf("      42: %s\n", ptr);
	free(ptr);
	printf("----------------\n");
	ptr2 = ft_itoa(n2);
	printf("       0: %s\n", ptr2);
	free(ptr2);
	printf("----------------\n");
	ptr3 = ft_itoa(n3);
	printf("     -42: %s\n", ptr3);
	free(ptr3);
	printf("----------------\n");
	ptr4 = ft_itoa(n4);
	printf(" INT_MAX: %s\n", ptr4);
	free(ptr4);
	printf("----------------\n");
	ptr5 = ft_itoa(n5);
	printf(" INT_MIN: %s\n", ptr5);
	free(ptr5);
	printf("----------------\n");
	ptr6 = ft_itoa(c);
	printf("char 'a': %s\n", ptr6);
	free(ptr6);
}
*/