Adition numbers as a char* [C++] without string.h

I want to add two numbers that are in char*. For example:

char aux1[100];
char aux2[100];
char answer[100];


answer= aux1+aux2; //1001

Of course the last line is wrong. I tried using atoi, but I cant use string library. I going to add numbers that cant join in int or long int. I can only use char* and the answer must be in char*.

The same for subtract "-". If is a negative number the symbol go to the first position 0.

I was thinking transform digit to digit and solve it, but i dont know.

1 answer

  • answered 2018-11-08 01:12 eerorika

    You can use the following algorithm. It may be familiar to you from elementary school:

    • Pad the shorter string with leading zeroes so that lengths are equal.
    • Let Carry be 0.
    • Starting from the last index:
      • Convert the character in the current index of both input strings into the numeric value that the character represents. Add Carry and both input digits together. The result will be a number AB where A and B are digits (possibly 0).
      • Set output digit at current index to B.
      • Set Carry to A.
      • Repeat until the entire string has been processed.

    I'll leave the handling of the negative numbers as an exercise.