题目描述
实现大数乘法,输入是两个字符串如
n1 = '340282366920938463463374607431768211456'
n2 = '340282366920938463463374607431768211456'
输出
'115792089237316195423570985008687907853269984665640564039457584007913129639936'
要求:不能使用对大数相乘有内建支持的语言;需要包含对输入字符串的合法性校验
输入描述:
一行,两个非负整数n1,n2,保证|n1|+|n2|<10000,其中|n|是n作为字符串的长度
输出描述:
输出n1*n2的结果
示例1
输入
复制
340282366920938463463374607431768211456 340282366920938463463374607431768211456
输出
复制
115792089237316195423570985008687907853269984665640564039457584007913129639936
说明
备注:
给出的数据均是合法的,但仍建议您对输入的字符串进行合法性校验
#include <bits/stdc++.h>
using namespace std;
int main()
{
string st1,st2;
cin>>st1;
cin>>st2;
int n = st1.size(),m = st2.size();
int a[n + m];
fill(a, a + n + m, 0);
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
a[n + m - i - j - 2] += (st1[i] - '0') * (st2[j] - '0');
for (int i = 0; i < n + m - 1; ++i)
{
a[i + 1] += a[i] / 10;
a[i] %= 10;
}
int r = n + m - 1;
for (; r && !a[r]; r--);
for (;r >= 0;--r)
cout<<a[r];
cout<<endl;
return 0;
}
标签:大数,int,340282366920938463463374607431768211456,st1,st2,n1,n2,乘法 From: https://blog.51cto.com/u_13121994/5798293