Long Integer adder-add large Integers
Read as characters, flip, and add and output.
//Long integer Adder#include<iostream>#include<cstdlib>using namespace std;void input(int a[],int b[],int& size1,int& size2);void process(int a[],int b[],int c[]);void output(int c[]);int main(){int a[20] = {0},b[20] = {0},c[20] = {0};int size1 = 0,size2 = 0;//a[20]=b[20]=c[20]={0};input(a,b,size1,size2);//cout<<a[0]<<" "<<a[2]<<" "<<b[0]<<" "<<b[2]<<endl;process(a,b,c);//cout<<c[0]<<endl;cout<<"The sum of the two numbers is : ";output(c);return 0; }void input(int a[],int b[],int& size1,int& size2){cout<<"Please inout two numbers:\n";char ch;int i = 0;int tem;cin.get(ch);while(ch >= ‘1‘ && ch <= ‘9‘){a[i] = static_cast<int>(ch)-48;size1 ++;i++;cin.get(ch);}//cout<<size1<<endl;cin.get(ch);i = 0;while(ch >= ‘1‘ && ch <= ‘9‘){b[i] = static_cast<int>(ch)-48;size2 ++;i++;cin.get(ch);}//cout<<size2<<endl;for(int i = 0;i < size1/2;i++){ tem = a[i]; a[i] = a[size1 - i - 1]; a[size1 - i - 1] = tem;}for(int i = 0;i < size2/2;i++) { tem = b[i]; b[i] = b[size2 - i -1]; b[size2 - i -1] = tem; }} void process(int a[],int b[],int c[]){int i = 0;while(i < 19) { //cout<<a[i]<<" "<<b[i]<<endl;if((a[i] + b[i]) >= 10){c[i] += a[i] + b[i] - 10;c[i+1] =c[i+1] + 1;//cout<<c[i+1]<<endl;}else c[i] += a[i] + b[i];//cout<<c[i]<<endl;i++;}//cout<<c[3]<<endl;} void output(int c[]){int i;for(i = 19;c[i] == 0; i--);//cout<<i<<endl;for(int j = i;j >= 0;j--)cout<<c[j];cout<<endl; }
Result:
Please inout two numbers:1234 5678The sum of the two numbers is : 6912
Please inout two numbers:123 456666The sum of the two numbers is : 456789
Long Integer adder-add large Integers