-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathint_to_string.c
More file actions
69 lines (63 loc) · 896 Bytes
/
int_to_string.c
File metadata and controls
69 lines (63 loc) · 896 Bytes
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
#include "shell.h"
/**
* int_string - turns int to string
* @num: integer
* Return: int to string
*/
char *int_string(int num)
{
char *result;
int j = 0;
int n = 0;
int k;
int sign = num;
int ten = 1;
if (num < 0)
j = 1;
result = malloc(sizeof(char) * (number_len(sign) + 2 + j));
if (result == NULL)
return (NULL);
if (num < 0)
{
result[n] = '-';
n++;
}
for (k = 0; sign > 9 || sign < -9; k++)
{
sign /= 10;
ten *= 10;
}
for (sign = num; k >= 0; k--)
{
if (sign < 0)
{
result[n] = (sign / ten) * -1 + '0';
n++;
}
else
{
result[n] = (sign / ten) + '0';
n++;
}
sign %= ten;
ten /= 10;
}
result[n] = '\0';
return (result);
}
/**
* number_len - count zeros
* @num: numbers
* Return: count of numbers
*/
int number_len(int num)
{
int sum = 0;
int n = num;
while (n > 9 || n < -9)
{
n /= 10;
sum++;
}
return (sum);
}