Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

C++大整数乘法,一遍过

Posted by Chan_keyword at 2020-01-30 18:56:56 on Problem 1001
/*
主要思路是首先去掉小数点同时记录小数点位置,然后用大整数乘法相乘n次,最后将小数点还原到结果中,需要注意的就是去前导零以及后面多余的0,以及整数处理(整数不能输出小数点),如果小数点位置大于结果长度应在前面补0,同时最前面的0不能写
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
string Mul(string s1, string s2)
{
	reverse(s1.begin(), s1.end());
	reverse(s2.begin(), s2.end());
	vector<int> v(s1.size() + s2.size(), 0);
	for (int i = 0; i < s1.size(); i++)
	{
		for (int j = 0; j < s2.size(); j++)
		{
			v[i + j] += (s1[i] - '0') * (s2[j] - '0');
		}
	}
	for (int i = 0; i < v.size() - 1; i++)
	{
		if (v[i] >= 10)
		{
			v[i + 1] += v[i] / 10;
			v[i] %= 10;
		}
	}
	string ans;
	int i;
	for (i = v.size() - 1; i > 0 && v[i] == 0; i--)
		;
	for (; i >= 0; i--)
	{
		ans += (char)(v[i] + '0');
	}
	return ans;
}
int main()
{
	string s1;
	int s2;
	while(cin>>s1>>s2)
	{
		int t,j;
		string ans="1";
		t=s1.find('.');//找到小数点位置
		s1=s1.substr(0,t)+s1.substr(t+1);//去小数点
		t=s1.length()-t;//小数位数
		for(int i=0;i<s2;i++)
		{
			ans=Mul(ans,s1);
		}
		/*以下还原小数点*/
		t=t*s2;//总小数点位数

		int L=ans.length();
		if(t<=ans.length())//直接插入小数点
		{
			ans=ans.substr(0,L-t)+"."+ans.substr(L-t);
		}
		else//前面补0
		{
			for(int i=0;i<t-L;i++)
				ans="0"+ans;
			ans="."+ans;//最后再加一个小数点
		}
		/*以下去后面多余的0(前导0在乘法算法中已经去除)*/
		L=ans.length();
		j=L-1;
		for(;j>=0&&ans[j]=='0';j--);
		if(ans[j]=='.')
			ans=ans.substr(0,j);
		else
			ans=ans.substr(0,j+1);
		cout<<ans<<endl;
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator