cszdls @ 2023-09-22 18:35:00
#include<bits/stdc++.h>
using namespace std;
const int MAXT=5000;
char s1[MAXT],s2[MAXT];
int a[MAXT]={0},b[MAXT]={0},c[MAXT]={0};
int main()
{
int len1,len2,lmax,x=0,n=0;
scanf("%s%s",&s1,&s2);
len1=strlen(s1);
len2=strlen(s2);
//倒放存入
for(int i=0;i<len1;i++)
{
a[i]=s1[len1-1-i]-'0';
}
for(int i=0;i<len2;i++)
{
b[i]=s2[len2-1-i]-'0';
}
//运算
for(int i=0;i<len1;i++)
{
for(int j=0;j<len2;j++)
{
n=a[i]*b[j]%10;
c[i+j]+=n+x;
x=a[i]*b[j]/10;
}
}
c[len1+len2-1]=x;
for(int i=0;i<len1;i++)
{
for(int j=0;j<len2;j++)
{
if(c[i+j]>=10)
{
n=c[i+j]%10;
x=c[i+j]/10;
c[i+j]=n;
c[i+j+1]+=x;
}
}
}
if(c[len1+len2-1]>=10)
{
n=c[len1+len2-1]%10;
c[len1+len2-1]=n+x;
x=c[len1+len2-1]/10;
}
c[len1+len2]=x;
lmax=len1+len2-1;
//消零
for(int i=0;i<lmax;i--)
{
if(c[lmax]==0 and lmax!=0)
{
lmax--;
}
else
{
break;
}
}
//输出
for(int i=lmax;i>=0;i--)
{
cout<<c[i];
}
return 0;
}
by Argvchs @ 2023-09-22 18:38:10
@cszdls
for(int i=0;i<lmax;i--)
by cszdls @ 2023-09-22 18:42:25
@Argvchs 请问那是应该怎么改一下呢?
by LoadingSpace @ 2023-09-22 19:25:57
@cszdls for(int i=0;i<lmax;i--) 有没有一种可能,这样写i一直小于lmax,导致死循环
by shengyeqi @ 2023-09-22 19:30:42
@cszdls
改了一下过了
#include <bits/stdc++.h>
using namespace std;
const int MAXT = 50000;
const int BASE = 10;
void multiply(string s1, string s2) {
int len1 = s1.length();
int len2 = s2.length();
vector<int> a(len1);
vector<int> b(len2);
vector<int> c(len1 + len2, 0);
// 将字符转换为数字,并反转字符串以便从低位到高位相乘
for (int i = 0; i < len1; i++) {
a[i] = s1[len1 - 1 - i] - '0';
}
for (int i = 0; i < len2; i++) {
b[i] = s2[len2 - 1 - i] - '0';
}
// 高精度乘法
for (int i = 0; i < len1; i++) {
for (int j = 0, carry = 0; j < len2 || carry; j++) {
long long product = c[i + j] + (long long)a[i] * (j < len2 ? b[j] : 0) + carry;
c[i + j] = product % BASE;
carry = product / BASE;
}
}
// 找到最高非零位
int lmax = len1 + len2 - 1;
while (lmax >= 0 && c[lmax] == 0) {
lmax--;
}
// 输出结果
if (lmax == -1) {
cout << "0";
} else {
for (int i = lmax; i >= 0; i--) {
cout << c[i];
}
}
}
int main() {
string s1, s2;
cin >> s1 >> s2;
multiply(s1, s2);
return 0;
}
by cszdls @ 2023-09-22 19:50:21
@shen @shengyeqin 谢谢大神,过了,感谢,明白了
by cszdls @ 2023-09-22 19:50:57
@LoadingSpace 谢谢,看到了,已经改好了,感谢帮助
by cszdls @ 2023-09-22 19:51:40
@Argvchs 感谢大神,已经过了
by shengyeqi @ 2023-09-22 19:53:04
@cszdls
求关注
by LoadingSpace @ 2023-09-22 22:09:59
@shengyeqin 你主页链接很好看,关了
by shengyeqi @ 2023-09-23 06:07:26
@LoadingSpace 薛薛