-
Notifications
You must be signed in to change notification settings - Fork 0
/
103-infinite_add.c
78 lines (71 loc) · 1.25 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
#include "main.h"
/**
* rev_string - reverse array
* @n: integer params
* Return: 0
*/
void rev_string(char *n)
{
int i = 0;
int j = 0;
char temp;
while (*(n + i) != '\0')
{
i++;
}
i--;
for (j = 0; j < i; j++, i--)
{
temp = *(n + j);
*(n + j) = *(n + i);
*(n + i) = temp;
}
}
/**
* infinite_add - add 2 numbers together
* @n1: text representation of 1st number to add
* @n2: text representation of 2nd number to add
* @r: pointer to buffer
* @size_r: buffer size
* Return: pointer to calling function
*/
char *infinite_add(char *n1, char *n2, char *r, int size_r)
{
int overflow = 0, i = 0, j = 0, digits = 0;
int val1 = 0, val2 = 0, temp_tot = 0;
while (*(n1 + i) != '\0')
i++;
while (*(n2 + j) != '\0')
j++;
i--;
j--;
if (j >= size_r || i >= size_r)
return (0);
while (j >= 0 || i >= 0 || overflow == 1)
{
if (i < 0)
val1 = 0;
else
val1 = *(n1 + i) - '0';
if (j < 0)
val2 = 0;
else
val2 = *(n2 + j) - '0';
temp_tot = val1 + val2 + overflow;
if (temp_tot >= 10)
overflow = 1;
else
overflow = 0;
if (digits >= (size_r - 1))
return (0);
*(r + digits) = (temp_tot % 10) + '0';
digits++;
j--;
i--;
}
if (digits == size_r)
return (0);
*(r + digits) = '\0';
rev_string(r);
return (r);
}