52 高精度乘法

52 高精度乘法

作者: Turbo时间限制: 1S章节: 基本练习(数组)

问题描述 :

  在C/C++语言中,整型所能表示的范围一般为-231到231(大约21亿),即使long long型,一般也只能表示到-263到263。要想计算更加规模的数,就要用软件来扩展了,比如用数组或字符串来模拟更多规模的数及共运算。
  现在输入两个整数,请输出它们的乘积。

输入说明 :

  两行,每行一个正整数,每个整数不超过10000位

输出说明 :

  一行,两个整数的乘积。

输入范例 :
10000
234
输出范例 :
2340000

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
	string str1, str2;
	cin >> str1 >> str2;
	int len1 = (int)str1.length();
	int len2 = (int)str2.length();
	int *p = new int[len1 + len2]();//数组初始化
	reverse(str1.begin(), str1.end());
	reverse(str2.begin(), str2.end());
	for (int i = 0; i < len1; i++)
	{
		for (int j = 0; j < len2; j++)
		{
			p[i + j] += (str1[i] - '0')*(str2[j] - '0');
		}
	}
	for (int i = 0; i < len1+ len2; i++)
	{
		p[i + 1] += p[i] / 10;
		p[i] %= 10;
	}
	int len = len1 + len2 - 1;
	while (len>=0&&p[len] == 0)
	{
		len--;
	}
	if (len < 0)
		cout << 0 << endl;
	else
	{
		len++;
		reverse(p, p + len);
		for (int i = 0; i < len; i++)
		{
			cout << p[i];
		}
		cout << endl;
	}
	return 0;
}
Yesterday is history,tomorrow ismystery,but today is a gift!That why it is called Present!
原文地址:https://www.cnblogs.com/VictorierJwr/p/12864701.html