建议加强数据

P1303 A*B Problem

2Bxzj @ 2023-07-15 17:21:24

我的代码

#include <iostream>
#include <string>
#include <cmath>
using namespace std;
string sa, sb;
long long a[2100], b[2100], c[4200];
int main ()
{
    cin >> sa >> sb;
    long long j = 1;
    for(long long i = sa.length() - 1; i >= 0; i--)
    {
        a[j] = sa[i] - '0';
        j++;
    }
    j = 1;
    for(long long i = sb.length() - 1; i >= 0; i--)
    {
        b[j] = sb[i] - '0';
        j++;
    }
    if(a[1] == 0 || b[1] == 0) 
    {
        cout << 0;
        return 0;   
    } 
    long long alen = sa.length(), blen = sb.length();
    long long len = alen + blen;
    for(long long i = 1; i <= alen; i++)
    {
        for(long long j = 1; j <= blen; j++)
        {
            c[i + j - 1] += a[i] * b[j];
        }
    }
    for(long long i = 1; i <= len; i++)
    {
        c[i + 1] += c[i] / 10;
        c[i] %= 10;
    }
    while(c[len] == 0)
    {
        len--;
    }
    for(long long i = max((long long)1, len); i >= 1; i--) cout << c[i];
    return 0;
}

提交: 100

但是

50 * 49

算出来是0

顺便求大佬帮我调一调


by ToastBread @ 2023-07-15 17:31:01

#include <iostream>
#include <string>
#include <cmath>
using namespace std;
string sa, sb;
long long a[2100], b[2100], c[4200];
int main ()
{
    cin >> sa >> sb;
    long long j = 1;
    for(long long i = sa.length() - 1; i >= 0; i--)
    {
        a[j] = sa[i] - '0';
        j++;
    }
    j = 1;
    for(long long i = sb.length() - 1; i >= 0; i--)
    {
        b[j] = sb[i] - '0';
        j++;
    }
    if(sa=="0"||sb=="0") 
    {
        cout << 0;
        return 0;   
    } 
    long long alen = sa.length(), blen = sb.length();
    long long len = alen + blen;
    for(long long i = 1; i <= alen; i++)
    {
        for(long long j = 1; j <= blen; j++)
        {
            c[i + j - 1] += a[i] * b[j];
        }
    }
    for(long long i = 1; i <= len; i++)
    {
        c[i + 1] += c[i] / 10;
        c[i] %= 10;
    }
    while(c[len] == 0)
    {
        len--;
    }
    for(long long i = max((long long)1, len); i >= 1; i--) cout << c[i];
    return 0;
}

50 你的高精判断的是个位,50的个位是0,所以会错

if(a[1] == 0 || b[1] == 0) 
    {
        cout << 0;
        return 0;   
    } 

要改为

if(sa=="0"||sb=="0") 
    {
        cout << 0;
        return 0;   
    } 

(只是一种改法


by 2Bxzj @ 2023-07-15 17:52:57

@ToastBread 谢谢


by Firrel_qaq @ 2023-07-15 17:55:17

同议,建议加强数据


|