-
Notifications
You must be signed in to change notification settings - Fork 0
/
103-infinite_add.c
81 lines (68 loc) · 1.8 KB
/
103-infinite_add.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
#include "main.h"
char *add_strings(char *n1, char *n2, char *r, int r_index);
char *infinite_add(char *n1, char *n2, char *r, int size_r);
/**
* add_strings - Adds the numbers stored in two strings.
* @n1: The string containing the first number to be added.
* @n2: The string containing the second number to be added.
* @r: The buffer to store the result.
* @r_index: The current index of the buffer.
*
* Return: If r can store the sum - a pointer to the result.
* If r cannot store the sum - 0.
*/
char *add_strings(char *n1, char *n2, char *r, int r_index)
{
int num, tens = 0;
for (; *n1 && *n2; n1--, n2--, r_index--)
{
num = (*n1 - '0') + (*n2 - '0');
num += tens;
*(r + r_index) = (num % 10) + '0';
tens = num / 10;
}
for (; *n1; n1--, r_index--)
{
num = (*n1 - '0') + tens;
*(r + r_index) = (num % 10) + '0';
tens = num / 10;
}
for (; *n2; n2--, r_index--)
{
num = (*n2 - '0') + tens;
*(r + r_index) = (num % 10) + '0';
tens = num / 10;
}
if (tens && r_index >= 0)
{
*(r + r_index) = (tens % 10) + '0';
return (r + r_index);
}
else if (tens && r_index < 0)
return (0);
return (r + r_index + 1);
}
/**
* infinite_add - Adds two numbers.
* @n1: The first number to be added.
* @n2: The second number to be added.
* @r: The buffer to store the result.
* @size_r: The buffer size.
*
* Return: If r can store the sum - a pointer to the result.
* If r cannot store the sum - 0.
*/
char *infinite_add(char *n1, char *n2, char *r, int size_r)
{
int index, n1_len = 0, n2_len = 0;
for (index = 0; *(n1 + index); index++)
n1_len++;
for (index = 0; *(n2 + index); index++)
n2_len++;
if (size_r <= n1_len + 1 || size_r <= n2_len + 1)
return (0);
n1 += n1_len - 1;
n2 += n2_len - 1;
*(r + size_r) = '\0';
return (add_strings(n1, n2, r, --size_r));
}