How to add two numbers as a string
chars
- 8-bit binary numbers like less ints
. We have to interpret them to give them meaning as letters.
Your computer may be using the ASCII standard. In ASCII, the value char
representing a character 0
does not actually have a numerical value of 0. It is 48. Fortunately, the numbers are all sequential, so it 1
is 49, and so on.
char zero = '0';
printf("%d\n", zero);
char one = '1';
printf("%d\n", one);
> 48
> 49
(Note that the format flag %d
in printf
means "interpret as an integer".)
Since they chars
are numbers, we can do math with them.
char one = '1';
int one_num = one - '0';
printf("%d\n", one_num);
> 1
Now you can implement decimal complement and carry over just like on paper.
source to share
Do it with programming just as you would on paper. Take small steps and make every little step explicitly we take on paper without noticing.
00111
---------
12345
123456789
---------
123469134
- Note the different lengths. You will need separate vars to store this information. You will need to find out two lengths, either use a standard function or write your own: strings are binary-terminated
0
. - Notice how we go back as we add. You will need to maintain two indices to access two strings (character arrays).
- Notice how we carry over the top digit of addition
5+9=14
. You will need to maintain this in another variable.
Use loops. Once you've added, you'll need to find out the total length and move it to the left edge. Since we don't know in advance how long we will get, you will start writing your answer from the right edge of your array sum
. Think about how and what you can improve on this.
source to share
If it is not prohibited, I would approach the following:
-
Convert the entered strings to numbers. I would try
strtol()
. -
Add numbers
-
Convert the sum from a number to a string. I would try
snprintf()
.
source to share