c++60分求助!

P1303 A*B Problem

yuxiaoyu20090104 @ 2022-09-12 12:13:17

#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
int a[5005], b[5005],c[6005];
int main()
{
    string A, B;
    cin >> A >> B;
    int lena = A.size(), lenb = B.size();
    int len = lena + lenb;
    for (int i = lena - 1; i >= 0; i--)
    {
        a[lena - i] = A[i] - '0';
    }
    for (int i = lenb - 1; i >= 0; i--)
    {
        b[lena - i] = B[i] - '0';
    }
    for (int i = 1; i <= lena; i++)
    {
        for (int j = 1; j <= lenb; j++)
        {
            c[i + j - 1] += a[i] * b[j];
        }
    }
    for (int i = 1; i <= len; i++)
    {
        c[i + 1] += c[i] / 10;
        c[i] %= 10;
    }
    if (c[len + 1])
    {
        len++;
    }
    while (!c[len])
    {
        len--;
    }
    for (int i = len; i >= 1; i--)
    {
        cout << c[i];
    }
    return 0;
}

by AcxxMz @ 2022-09-12 12:37:08

#include<bits/stdc++.h>
using namespace std;
string a,b;
int n1[2005],n2[2005],ans[4005];
int main()
{
    cin>>a>>b;
    int lena=a.size(),lenb=b.size();
    for(int i=0;i<=lena-1;i++)
        n1[lena-i]=a[i]-'0';
    for(int i=0;i<=lenb-1;i++)
        n2[lenb-i]=b[i]-'0';
    for(int i=1;i<=lenb;i++)
    {
        int x=0;
        for(int j=1;j<=lena;j++)
        {
            ans[i+j-1]+=n1[j]*n2[i]+x;
            x=ans[i+j-1]/10;
            ans[i+j-1]%=10;
        }
        ans[i+lena]+=x;
    }
    int lenc=lena+lenb;
    while(ans[lenc]==0&&lenc>1)
        lenc--;
    for(int i=lenc;i>=1;i--)
        cout<<ans[i];
    return 0;
}

可以看看我的


by shizengjie施锃杰 @ 2022-09-12 12:49:15

错误样例:

0
1

by yuxiaoyu20090104 @ 2022-09-12 13:01:48

for (int i = max(1, len); i >= 1; i--)
    {
        cout << c[i];
    }

@shizengjie施锃杰 改了之后是60分


by shizengjie施锃杰 @ 2022-09-12 13:06:45

 for (int i = lenb - 1; i >= 0; i--)
 {
        b[lena - i] = B[i] - '0';
 }

改成

 for (int i = lenb - 1; i >= 0; i--)
 {
        b[lenb - i] = B[i] - '0';
 }

by yuxiaoyu20090104 @ 2022-09-12 13:14:52

@shizengjie施锃杰 好了谢谢


by yuxiaoyu20090104 @ 2022-09-12 13:15:40

@1234aaa 谢谢


|