第五个点TLE求助!

P1303 A*B Problem

CZ_7 @ 2021-08-26 16:03:03

RT 思路是把乘法转换成每一位每一位乘

#include<bits/stdc++.h>
using namespace std;
int n;
string ans="1",s1;
string jia(string a,string b){
    string over="";
    int c=max(a.length(),b.length());
    for(int i=a.length();i<c;i++)a='0'+a;
    for(int i=b.length();i<c;i++)b='0'+b;
    int flag=0;
    for(int i=c-1;i>=0;i--){
        if(a[i]+b[i]+flag-'0'-'0'<=9){
            int shu=a[i]+b[i]+flag-'0'-'0';
            flag=0;
            over=to_string(shu)+over;
        }
        else{
            int shu=a[i]+b[i]+flag-'0'-'0'-10;
            flag=1;
            over=to_string(shu)+over;
        }
    }
    if(flag==1)over="1"+over;
    return over;
}
string yiweicheng(string a,char b){
    string over="";
    int flag=0;
    for(int i=a.length()-1;i>=0;i--){
        int shu=((a[i]-'0')*(b-'0')+flag)%10;
        int kk=((a[i]-'0')*(b-'0')+flag)/10;
        flag=kk;
        over=to_string(shu)+over;
    }
    if(flag>0)over=to_string(flag)+over;
    return over;
}
string cheng(string a,string b){
    string c="",d="";
    for(int i=0;i<b.length();i++){
        d=yiweicheng(a,b[i]);
        for(int j=1;j<b.length()-i;j++){
            d=d+"0";
        }
        c=jia(c,d);
    }
    return c;
}
int main(){
    string a,b;
    cin>>a>>b;
    if(a=="0"||b=="0"){
        cout<<"0";
        return 0;
    }
    cout<<cheng(a,b);
    return 0;
}

by CZ_7 @ 2021-08-28 23:13:51

@10circle

thanks 学到了!(dalao的代码果然简洁 stO


by yu_666 @ 2021-08-29 17:09:13

@CZ_7 哦


上一页 |