-
Notifications
You must be signed in to change notification settings - Fork 0
/
add.c
135 lines (89 loc) · 2.37 KB
/
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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* intal_add(const char *intal1, const char * intal2);
int main()
{
const char intal_1[1000] = "00";
const char intal_2[1000] = "0000";
printf("sol recieved %s\n",intal_add(intal_1, intal_2));
}
char* intal_add(const char* intal1, const char* intal2)
{
int len_1 = strlen(intal1);
int len_2 = strlen(intal2);
int diff_len = len_1 - len_2;
if(diff_len < 0)
{
diff_len = diff_len * -1;
}
//printf("DIFF in len %d\n", diff_len);
char * zero = malloc(sizeof(char) * (len_1 + len_2));
int i;
for(i=0;i<diff_len;i++)
{
*(zero + i) = '0';
}
*(zero + i) = '\0';
//printf("%s\n", zero);
//printf("%d\n",i);
int x, y, res, carry;
int p;
char* sol = (char *)malloc(sizeof(char*) * 1000);
carry = 0;
if(len_1 < len_2)
{
int sol_index = 0;
for (int j = 0; intal1[j] != '\0'; ++j, ++i)
{
*(zero + i) = intal1[j];
}
*(zero + i) = '\0';
//printf("%s\n", zero);
//printf("%s\n", intal2);
//Perform addition on zero and intal2
*(sol+len_2) = '\0';
for(p = len_2 -1; p >= 0; p--)
{
x = *(zero + p) - '0';
y = intal2[p] - '0';
res = x + y + carry;
carry = res / 10;
res = res % 10;
//printf("Store %d, Carry %d\n",res, carry);
*(sol + p + 1) = res + '0';
}
*(sol + p+1) = carry + '0';
*(sol+ p) = '\0';
//printf("%s\n",sol);
}
else
{
int sol_index = 0;
for (int j = 0; intal2[j] != '\0'; ++j, ++i)
{
*(zero + i) = intal2[j];
}
*(zero + i) = '\0';
//Perform addition on zero and intal1
*(sol+len_1) = '\0';
for(p = len_1 -1; p >= 0; p--)
{
x = *(zero + p) - '0';
y = intal1[p] - '0';
res = x + y + carry;
carry = res / 10;
res = res % 10;
*(sol+p+1) = res + '0';
//printf("Store %d, Carry %d\n",res, carry) ;
}
*(sol+p+1) = carry + '0';
*(sol+p) = '\0';
//printf("%s\n",sol);
}
while(*(sol + 0) == '0'&& *(sol + 1) != '\0')
{
sol++;
}
return sol;
}