Skip to content

Instantly share code, notes, and snippets.

@naxmefy
Created May 7, 2021 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naxmefy/c38b2092ccd00d47d093b595058507cc to your computer and use it in GitHub Desktop.
Save naxmefy/c38b2092ccd00d47d093b595058507cc to your computer and use it in GitHub Desktop.
Adding Big Numbers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *add(const char *a, const char *b) {
size_t pos_1, pos_2, pos_3, len_3;
unsigned int carry;
pos_1 = strlen(a);
pos_2 = strlen(b);
len_3 = pos_3 = (pos_1 > pos_2 ? pos_1 : pos_2) + 1;
char *result = malloc(pos_1 + 1);
strcpy(result, a);
result = realloc(result, len_3 + 1);
result[pos_3] = '\0';
for(carry = 0; pos_3 > 0; carry /= 10) {
if (pos_1 > 0) carry += result[--pos_1] - '0';
if (pos_2 > 0) carry += b[--pos_2] - '0';
result[--pos_3] = '0' + carry % 10;
}
while(result[0] == '0' && len_3 > 1) {
memmove(result, result + 1, len_3--);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment