-
Notifications
You must be signed in to change notification settings - Fork 3
/
num_help.c
64 lines (58 loc) · 1.11 KB
/
num_help.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
#include "shell.h"
/**
* _itoa - Function that converts a number to string
* @number: value to be converted to a string
* @buffer: array that stores null-termintated string result
* @base: value of the string
*
* Return: converted string
*/
char *_itoa(size_t number, char *buffer, int base)
{
int sign = 1, i = 0;
size_t remainder = 0;
/* if number is 0, hard code result */
if (number == 0)
{
buffer[i++] = '0';
buffer[i] = '\0';
}
/*
* if negative, convert to pos and track sign
* if (number < 0 && base == 10)
* {
* number *= -1;
* sign *= -1;
* }
*/
/* if number is not 0 */
while (number)
{
remainder = number % base;
buffer[i++] = '0' + remainder;
number /= base;
}
/* if negative, add sign char */
if (sign < 0)
buffer[i++] = '-';
/* terminate string */
if (number)
buffer[i] = '\0';
return (_revstr(buffer));
}
/**
* count_digit - Returns how many digits make up a number
* @num: The number to count the amount of digits
*
* Return: Always a size_t
*/
size_t count_digit(size_t num)
{
size_t count = 0;
while (num != 0)
{
num /= 10;
count++;
}
return (count);
}