I tried to implement the subtract method but got there are some bugs.
55-44 is correct
555-44 is not correct, it will return 011
100-44 will cause segmentation fault
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>
char* subtract(char *n1,char *n2){
int n1Len = strlen(n1);
int n2Len = strlen(n2);
int diff;
int max=n1Len;
char* res = (char*)malloc (max+2);
memset(res, '0', max +1);
res[max] = '\0';
int i=n1Len - 1, j = n2Len - 1, k = max;
for (; i >= 0 && j >=0; --i, --j, --k) {
if(i >= 0 && j>=0)
{
diff = (n1[i] - '0') - (n2[j] - '0');
if(diff<0)
{
int temp=n1[i-1]-'0';
temp=temp-1;
n1[i-1]=temp+'0';
diff+=10;
}
res[i]=diff+'0';
}
else
res[i]=n1[i];
}
return res;
}
int main(void) {
printf("%s\n", subtract("100","44"));
}
I wrote it in GMP just for kicks.