Long Integer adder-add large Integers

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.