-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconversion_operations.c
71 lines (66 loc) · 1.06 KB
/
conversion_operations.c
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
/* conversion_operations.c */
#include "shell.h"
/**
* _atoi - Converts a string to an integer.
*
* @string: String to be converted.
*
* Return: Integer value.
*/
long int _atoi(char *string)
{
int num = 0, count = 0;
if (string == NULL)
return (-1);
if (!string[1])
{
num = string[0] - '0';
return (num);
}
while (string[count] != '\0')
{
if (string[count] >= '0' && string[count] <= '9')
num = (num * 10) + (string[count] - '0');
else
return (-1);
count++;
}
return (num);
}
/**
* _itoa - Converts an integer to a string.
*
* @number: Integer to be converted.
*
* Return: String representation of the integer.
*/
char *_itoa(int number)
{
int nbr_digits = 0, temp;
char *string_int;
temp = number;
if (number == 0)
nbr_digits = 1;
else
{
while (number != 0)
{
number /= 10;
nbr_digits++;
}
}
string_int = malloc(sizeof(char) * (nbr_digits + 1));
if (string_int == NULL)
{
perror("malloc");
return (NULL);
}
string_int[nbr_digits] = '\0';
while (nbr_digits > 0)
{
string_int[nbr_digits - 1] = '0' + (temp % 10);
temp /= 10;
nbr_digits--;
}
return (string_int);
}