为什么超时?再悬关

P1303 A*B Problem

lucy2012 @ 2024-02-21 19:11:16

#include<bits/stdc++.h>                                                  
using namespace std;
int main(){
    string a,b;
    int a1[2005],b1[2005],sum[4005],ac,bc,num;
    cin>>a>>b;
    ac=a.length();
    bc=b.length();
    num=max(bc,ac);
    for(int i=ac-1;i>=0;i++)
        a1[i]=a[ac-i+1]-'0';
    for(int i=bc-1;i>=0;i++)
        b1[i]=b[bc-i+1]-'0';
    for(int i=0;i<=num*2;i++){
        sum[i]=a1[i]*b1[i];
        sum[i+1]=sum[i]/10;
        sum[i]=sum[i]%10;
    }
    while(num--){
        if(sum[num])
            break;
    }
    num++;
    for(int i=num;i>=0;i--){
        cout<<sum[i];
    }
    return 0;
}

by lucy2012 @ 2024-02-21 22:05:10

@wuboyan714 谢谢啦~(似乎很艰难de看懂了


by lucy2012 @ 2024-02-21 22:20:31

#include<bits/stdc++.h>                                                  
using namespace std;
int main(){
    string a,b;
    int a1[2005],b1[2005],sum[4005]={0},ac,bc,num;
    cin>>a>>b;
    ac=a.length();
    bc=b.length();
    num=ac+bc;
    for(int i=ac-1;i>=0;i++)
        a1[i]=a[ac-i+1]-'0';
    for(int i=bc-1;i>=0;i++)
        b1[i]=b[bc-i+1]-'0';
    for(int i=0;i<=ac;i++){
        for(int j=0;j<=bc;j++)
            sum[i+j]+=a1[i]*b1[j];
    }
    for(int i=0;i<=num;i++){
        sum[i+1]+=sum[i]/10;
        sum[i]%=10;
    }
    while(sum[num-1]==0&&num>1)
        num--;
    for(int i=num-1;i>=0;i--)
        cout<<sum[i];
    return 0;
}

上一页 |