-
Notifications
You must be signed in to change notification settings - Fork 1
/
print_i.c
71 lines (65 loc) · 964 Bytes
/
print_i.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
#include <stdio.h>
#include <stdarg.h>
#include "holberton.h"
#include <stdlib.h>
/**
* _abs - absolute value
* @n: int
* Return: n
*/
int _abs(int n)
{
if (n < 0)
n *= -1;
return (n);
}
/**
* print_i - print integer
* @list: va_list
* Return: string
*/
char *print_i(va_list list)
{
int digit = 0, i = 0, neg = 0;
int divisor = 1000000000;
char *output;
int num = va_arg(list, int);
int len = _numlen(num);
output = malloc(len * sizeof(char) + 1 + neg);
if (output == NULL)
{
free(output);
return (0);
}
if (num < 0)
{
neg++;
}
if (num < 0)
{
output[i] = '-';
i++;
}
if (num > -10 && num < 10)
{
output[i] = _abs(num) + '0';
return (output);
}
while (divisor)
{
digit = (num / divisor) % 10;
if (num < 0)
{
digit = _abs(digit);
}
if (digit != 0 || (len >= 0 && output[i - 1] >= '0'))
{
output[i] = digit + '0';
i++;
len--;
}
divisor /= 10;
}
output[i] = '\0';
return (output);
}