-
Notifications
You must be signed in to change notification settings - Fork 0
/
numbers.c
108 lines (101 loc) · 1.54 KB
/
numbers.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
106
107
108
#include "main.h"
/**
* arsize - calculates the size of an integer
* @n: integer to calculate size of
*
* Return: size of integer
*/
int arsize(int n)
{
int size = 0;
while (n % 10 != n)
{
n = n - (n % 10);
size += 1;
n = n / 10;
}
return (size + 1);
}
/**
* print_int - prints an integer to stdout
* @n: integer to print
*
* Return: size of integer printed
*/
int print_int(int n)
{
int digit, size, size2, i, sign = n;
char *array;
if (n == INT_MIN)
{
_printf("-2147483648");
return (11);
}
if (n < 0)
{
_putchar('-');
n = -n;
}
if (n == 0)
{
_putchar('0');
return (1);
}
else
{
size = arsize(n);
size2 = size;
array = malloc((sizeof(char) * size));
if (array == NULL)
{
free(array);
exit(EXIT_FAILURE);
}
while (n > 0)
{
digit = n % 10;
array[size - 1] = (digit + '0');
n /= 10;
size--;
}
for (i = 0; i < size2; i++)
_putchar(array[i]);
}
free(array);
if (sign >= 0)
return (size2);
else
return (size2 + 1);
}
/**
* print_binary - prints to stdout
* @n: integer to print
*
* Return: size of integer printed
*/
int print_binary(unsigned int n)
{
int count = 0;
if (n == 0)
{
_putchar('0');
return (1);
}
count = print_binary_recursion(n);
return (count);
}
/**
* print_binary_recursion - prints to stdout
* @n: integer to print
*
* Return: size of integer printed
*/
int print_binary_recursion(unsigned int n)
{
int count = 0;
if (n == 0)
return (0);
count = print_binary_recursion(n >> 1);
_putchar((n & 1) ? '1' : '0');
return (count + 1);
}