为什么高精度加法不能通过这题?

P1001 A+B Problem

mrbhsj @ 2024-07-27 16:26:54

#include<iostream>
#include<cstring>
using namespace std;
string add(string a,string b){
    string s;
    int la,lb,lc;
    int a1[1000]={},b1[1000]={},c[1000]={};
    la=a.length();
    lb=b.length();
    for(int i=0;i<la;i++){
        a1[i]=a[la-1-i]-'0';
    }
    for(int i=0;i<lb;i++){
        b1[i]=b[lb-1-i]-'0';
    }

    lc=max(la,lb);

    for(int i=0;i<lc;i++){
        c[i]=c[i]+a1[i]+b1[i];
        if(c[i]>=10){
            c[i+1]=c[i+1]+c[i]/10;
            c[i]=c[i]%10;
        }
    }

    if(c[lc]!=0) lc++;

    for(int i=lc-1;i>=0;i--){
        s=s+char(c[i]+48);
    }
    return s;
}
int main(){

    string a,b,c;
    cin>>a>>b;
    c=add(a,b);
    cout<<c;
    return 0;
}

by Grammar__hbw @ 2024-07-27 16:38:24

@King_and_Grey 使用__builtin_不用头文件


by Argvchs @ 2024-07-27 16:44:02

@King_and_Grey https://www.luogu.com.cn/record/168919563


by Argvchs @ 2024-07-27 16:44:35

@Grammar__hbw 完全不需要


by jiangyuan2011 @ 2024-07-28 10:02:57

include <bits/stdc++.h>

using namespace std; int num1[505],num2[505],jinwei[505],res[505]; string s1,s2; int main(){ cin>>s1>>s2; int l1=s1.size(); int l2=s2.size(); for(int i=0;i<l1;i++)num1[l1-1-i]=s1[i]-'0'; for(int i=0;i<l2;i++)num2[l2-1-i]=s2[i]-'0'; int l3=max(l1,l2)+1; for(int i=0;i<l3;i++){ res[i]=(num1[i]+num2[i]+jinwei[i])%10; jinwei[i+1]=(num1[i]+num2[i]+jinwei[i])/10; } if(res[l3-1]==0) l3--; for(int i=l3-1;i>=0;i--){ cout<<res[i];

}
return 0;

} ```c

include <bits/stdc++.h>

using namespace std; int num1[505],num2[505],jinwei[505],res[505]; string s1,s2; int main(){ cin>>s1>>s2; int l1=s1.size(); int l2=s2.size(); for(int i=0;i<l1;i++)num1[l1-1-i]=s1[i]-'0'; for(int i=0;i<l2;i++)num2[l2-1-i]=s2[i]-'0'; int l3=max(l1,l2)+1; for(int i=0;i<l3;i++){ res[i]=(num1[i]+num2[i]+jinwei[i])%10; jinwei[i+1]=(num1[i]+num2[i]+jinwei[i])/10; } if(res[l3-1]==0) l3--; for(int i=l3-1;i>=0;i--){ cout<<res[i];

}
return 0;

}


by jiangyuan2011 @ 2024-07-28 10:04:54

@mrbhsj

#include <bits/stdc++.h>
using namespace std;
int num1[505],num2[505],jinwei[505],res[505];
string s1,s2;
int main(){
    cin>>s1>>s2;
    int l1=s1.size();
    int l2=s2.size();
    for(int i=0;i<l1;i++)num1[l1-1-i]=s1[i]-'0';
    for(int i=0;i<l2;i++)num2[l2-1-i]=s2[i]-'0';
    int l3=max(l1,l2)+1;
    for(int i=0;i<l3;i++){
        res[i]=(num1[i]+num2[i]+jinwei[i])%10;
        jinwei[i+1]=(num1[i]+num2[i]+jinwei[i])/10;
    }
    if(res[l3-1]==0) l3--;
    for(int i=l3-1;i>=0;i--){
        cout<<res[i];

    }
    return 0;
} 

上一页 |