The logic behind this is to store the large number as string and operate on each character as string is an array of characters each digit of the number is stored as a character. In order to work with characters there are two ways to do:
1.To write our own arithmetic operators to work with characters (overloading of operators)
2.Convert a character into an integer, work on integers and convert back to a character.
2.Convert a character into an integer, work on integers and convert back to a character.
How to convert a character into an integer?
Method 1:
If we have a character c='10'.We can follow one of these steps:
If we have a character c='10'.We can follow one of these steps:
int a
a=(int)c //a has ascii value of 'c' i.e 58
c=c-48 //58-48=10
Ascii value of the digit can be obtained by adding 48 to the digit.
Method 2:
int a
a=c-'0' // i.e 58-48=10&a contains 10
The character '0' means 48Note: To convert from char to integer subtract ‘0’ and to convert from an integer to char add ‘0’
Here is the program to add two large numbers
#include <iostream> | |
#include <cstdlib> | |
#include <string> | |
using namespace std; | |
int main() | |
{ | |
string str1="1234567891011121314151617181920", str2="1234567891011121314151617181920" ; | |
string rev_str1, rev_str2; | |
string final; //Final product string | |
int carry = 0; | |
rev_str1 = string(str1.rbegin(), str1.rend()); | |
rev_str2 = string(str2.rbegin(), str2.rend()); | |
for (int i = 0; i <rev_str1.length() ; i++) | |
{ | |
int x=rev_str1[i]-'0'; //converting into integer | |
int y=rev_str2[i]-'0'; | |
int z=x+y+carry; | |
final+=('0'+z%10); //converting into character | |
carry=z/10; | |
} | |
if(carry>0) //final carry | |
final+='0'+carry; | |
final = string(final.rbegin(), final.rend()); | |
cout << "final = " << final << endl; | |
} |
This numerical example gives better understanding of the program.
str1="129" str2="234"
rev_str1="921".rev_str2="432"
carry=0
i=0 to 2
i=0
x='9'-'0'=57-48=9
y='4'-'0'=52-48=4
z=9+4+0 //carry=0 for 1st iteration
final +='0'+13%10='3'
carry=13/10=1
i=1
x='2'-'0'=50-48=2
y='3'-'0'=51-48=3
z=2+3+1 //carry=1
final +='0'+5%10='6' //final="3"
carry=5/10=0
i=2
x='1'-'0'=59-48=1
y='2'-'0'=50-48=2
z=1+2+0 //carry=0
final +='0'+3%10='3' //final="36"
carry=3/10=0
final="363"