Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverse(char str[]);
void add(char num1[], char num2[], char sum[]);
int main(int argc, char** argv)
{
int n, i;
char num1[200], num2[200], sum[210];
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%s %s", num1, num2);
reverse(num1);
reverse(num2);
add(num1, num2, sum);
reverse(sum);
printf("%s\n", sum);
}
return 0;
}
void add(char num1[], char num2[], char sum[])
{
int len1 = strlen(num1);
int len2 = strlen(num2);
int len = len1 > len2 ? len1 : len2;
int i;
char d1, d2, d3;
int carry = 0;
reverse(num1);
reverse(num2);
for(i = 0; i < len; i++)
{
if(i < len1)
{
d1 = num1[i] - '0';
}
if(i < len2)
{
d2 = num2[i] - '0';
}
d3 = d1 + d2 + carry;
d1 = 0;
d2 = 0;
if(d3 >=10)
{
carry = 1;
sum[i] = (d3 - 10) + '0';
}
else
{
carry = 0;
sum[i] = d3 + '0';
}
}
if(carry == 1)
{
sum[len] = '1';
sum[len+1] = '\0';
}
else
{
sum[len] = '\0';
}
reverse(sum);
}
void reverse(char str[])
{
int i, length = strlen(str);
for(i = length-1; i >= 0; i--)
{
if(str[i] == '0')
{
str[i] = '\0';
}
else
{
break;
}
}
length = strlen(str);
int halflength = length / 2;
for(i = 0; i < halflength; i++)
{
str[i]^=str[length-i-1];
str[length-i-1]^=str[i];
str[i]^=str[length-i-1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.