悬2关高精乘法板子红题求助

P1303 A*B Problem

zhangmingsheng3521 @ 2023-08-24 22:14:00

rt.代码只要碰到要进位的情况就会炸.

代码如下(AC给关,但是大框架不能改,有注释,相对友好)

#include"bits/stdc++.h" 
using namespace std;
int a[2002],b[2002],c[4004];//a,b乘数c积
int main()
{
    int mark;
    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
    memset(c,0,sizeof(c));
    string s;
    cin>>s;//读入
    int n1=s.size();
    for (int i=0;i<n1;i++)
    {
        a[i]=int(s[i])-48;
    }
    cin>>s; 
    int n2=s.size();
    for (int i=0;i<n2;i++)
    {
        b[i]=int(s[i])-48;
    }
    for (int i=0;i<n1;i++)
    {
        for (int j=0;j<n2;j++)
        {
            c[i+j]+=a[i]*b[j];//乘法
            c[i+j+1]+=c[i+j]/10;//进位
            c[i+j]=c[i+j]%10;
        }
    }
    for (int i=4003;i>=1;i--)//定位首个非0
    {
        if (c[i]!=0)
        {
            mark=i;
            break;
        }
    }
    for (int i=0;i<=mark;i++)//输出
    {
        printf("%d",c[i]);
    } 
    return 0;
}

by gfgoodluck @ 2023-08-24 22:37:47

一共就改了三处(


by OIerWu_829 @ 2023-08-24 22:39:06

#include <bits/stdc++.h>
using namespace std;
int a[2005], b[2005], c[4005];
int main(){
    string sa, sb;
    cin >> sa >> sb;
    if (sa == "0" || sb == "0")
    {
        cout << 0;
        return 0;
    }
    int la = sa.length();
    int lb = sb.length();
    int lc = la + lb;
    for (int i = 0; i < la; i++)
        a[i] = sa[la - i - 1]-'0';
    for (int i = 0; i < lb; i++)
        b[i] = sb[lb - i - 1]-'0';
    for (int i = 0; i < la; i++)
        for (int j = 0; j < lb; j++)
            c[i + j] += a[i] * b[j];
    for (int i = 0; i < lc; i++)
    {
        c[i + 1] += (c[i] / 10);
        c[i] %= 10;
    }
    while (!c[lc])
    {
        lc--;
    }
    for (int i = lc; i >= 0; i--)
        cout << c[i];

    return 0;
}

by zhangmingsheng3521 @ 2023-08-24 22:40:08

@gfgoodluck %%%,拿小号已关


by renchengxin @ 2023-08-27 16:50:05

@zhangmingsheng3521 第一个测试点过了么


上一页 |