-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintegers.c
105 lines (91 loc) · 1.52 KB
/
integers.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
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
#include "main.h"
#include <stdlib.h>
/**
* _int - determine the integer base and print the decimal ones
* @ap: list of the passed arguments
*
* Return: number of the printed characters (int)
*/
int _int(va_list ap)
{
int t, count;
char *s, *p;
t = va_arg(ap, int);
if (t == 0)
{
_putchar('0');
return (1);
}
s = int_stringify(t);
p = s;
if (*s == '0' && *(s + 1) == 'x')
p = base(s, 16);
else if (*s == '0' && (*(s + 1) == 'b' || *(s + 1) == 'B'))
p = base(s, 2);
else if (*s == '0' && *(s + 1))
p = base(s, 8);
count = 0;
while (*p)
{
_putchar(*p++);
count++;
}
free(s);
return (count);
}
/**
* int_length - determine the length of number recursively
* @num: the passed number
*
* Return: the length of the number (int)
*/
int int_length(int num)
{
if (num == 0)
return (0);
return (1 + int_length(num / 10));
}
/**
* int_stringify - converts a number to a string
* @num: the passed number to be converted
*
* Return: pointer to the converted string (char*)
*/
char *int_stringify(long int num)
{
char *str, *p;
int negative = 0, len = 0, i;
if (num < 0)
{
negative = 1;
num *= -1;
len = int_length(num) + 1;
}
else
{
len = int_length(num);
}
str = malloc(sizeof(char) * len + 1);
if (!str)
{
free(str);
return (0);
}
p = str;
while (num)
{
*str = num % 10 + '0';
num /= 10;
str++;
}
if (negative)
*str++ = '-';
*str = '\0';
for (i = 0; i < len / 2; i++)
{
p[i] ^= p[len - 1 - i];
p[len - 1 - i] ^= p[i];
p[i] ^= p[len - 1 - i];
}
return (p);
}