_lyc @ 2023-07-17 20:25:53
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 2e3+10;
int a[MAXN],b[MAXN],ans[MAXN*2],len1,len2,cnt;
char num1[MAXN],num2[MAXN];
int main(){
cin>>num1>>num2;
len1 = strlen(num1),len2 = strlen(num2),cnt = len1+len2;
for(int i = len1-1,j = 1;i >= 0;i--,j++) a[j] = num1[i] - '0';
for(int i = len2-1,j = 1;i >= 0;i--,j++) b[j] = num2[i] - '0';
for(int i = 1;i <= len1;i++)
for(int j = 1;j <= len2;j++) ans[i+j-1] += a[i]*b[j];
for(int i = 1;i <= len1+len2;i++){
ans[i+1] += ans[i]/10;
ans[i] %= 10;
}
while(!ans[cnt]) cnt--;
for(int i = cnt;i >= 1;i--) cout<<ans[i];
return 0;
}
不知为何,第一个点WA(输出对了
by Minecraftmine @ 2023-07-17 20:35:32
while(!ans[cnt]) cnt--;
改成
while(ans[cnt]==0 && cnt>1) cnt--;
by Minecraftmine @ 2023-07-17 20:36:27
@lyc0613
by bookchong @ 2023-07-17 20:49:10
你应该加个特判。如果num1或者num2为0,则最后的答案为0.所以如果num1或num2为0,直接输出0即可
所以在main函数中添加
if(num1 == "0" || num2 == "0") cout << 0 << endl;
就行
完整代码(我把你用的char改成了string)
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 2e3+10;
int a[MAXN],b[MAXN],ans[MAXN*2],len1,len2,cnt;
string num1,num2;
int main(){
cin>>num1>>num2;
if(num1 == "0" || num2 == "0") cout << 0 << endl;
len1 = num1.size(),len2 = num2.size(),cnt = len1+len2;
for(int i = len1-1,j = 1;i >= 0;i--,j++) a[j] = num1[i] - '0';
for(int i = len2-1,j = 1;i >= 0;i--,j++) b[j] = num2[i] - '0';
for(int i = 1;i <= len1;i++)
for(int j = 1;j <= len2;j++) ans[i+j-1] += a[i]*b[j];
for(int i = 1;i <= len1+len2;i++){
ans[i+1] += ans[i]/10;
ans[i] %= 10;
}
while(!ans[cnt]) cnt--;
for(int i = cnt;i >= 1;i--) cout<<ans[i];
return 0;
}
by _lyc @ 2023-07-17 20:51:07
@Minecraftmine @Sun09426 已AC,感谢神犇