大数相加-cpp

2023-02-06 19:00:37 浏览数 (2)

代码语言:javascript复制
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
    string a,b,c;
    int length_a,length_b;
    cin>>a;
    cin>>b;
    length_a=a.length();
    length_b=b.length();
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    if(length_a>=length_b)
    {
        for(int i=0;i<(length_a-length_b);i  )
        {
            b.append(1,'0');
        }
    }
    else
    {
        for(int i=0;i<(length_b-length_a);i  )
        {
            a.append(1,'0');
        }
    }

    
cout<<a<<endl;
cout<<b<<endl;

    if(length_a>=length_b)
    {
        for(int i=0;i<length_a;i  )
        {
            a[i]-='0';
            b[i]-='0';
            if((a[i] b[i])>=10)
            {
                c.append(1,(a[i] b[i]));
                a[i 1]  ;
                c[i] ='0';
            }
            else
            {
                c.append(1,a[i] b[i]);
                c[i] ='0';
            }

        }
    }
    else
    {
        for(int i=0;i<length_b;i  )
        {
            a[i]-='0';
            b[i]-='0';
            if((a[i] b[i])>=10)
            {
                c.append(1,(a[i] b[i]));
                b[i 1]  ;
                c[i] ='0';

            }
            else
            {
                c.append(1,a[i] b[i]);
                c[i] ='0';

            }

        }

    }

    
    reverse(c.begin(),c.end());
    int length_c=c.length();

    cout<<c;
}

时间复杂度O(n);

0 人点赞