Bull Math (大数乘法)

Bulls are so much better at math than the cows. They can multiply huge integers together and get perfectly precise answers ... or so they say. Farmer John wonders if their answers are correct. Help him check the bulls' answers. Read in two positive integers (no more than 40 digits each) and compute their product. Output it as a normal number (with no extra leading zeros). 

FJ asks that you do this yourself; don't use a special library function for the multiplication.

Input

* Lines 1..2: Each line contains a single decimal number.

Output

* Line 1: The exact product of the two input lines

Sample Input

11111111111111
1111111111

Sample Output

12345679011110987654321

思路:

1.移位:对于两个数a=12,b=25,在相乘的时候我们让每一位数分别相乘,即a[0]*b[0]=2 , a[0]*b[1]=5 , a[1]*b[0]=4 , a[1]*b[1]=10,那么规律就是,对于两个数a[i] , b[j],所有i+j相同的数都要加到一起,所以我们要把5+4=9合并为一个数,也就是说,将每一位数相乘之后,我们实际得到了2,9,10三个没有进位的数

2.进位:通过上面的操作,我们的2,9,10三个没有进位的数,下面就要进行进位,因为我们是把高位相乘得到的数放在前面,地位相乘得到的数放在后面,所以这三个数排列自然也是高位在前,地位在后,所以要从右向左进位,进位的方法就是a[i]+=a[i+1]/10 , a[i+1]%=10,如果放到这三个数上面,就是,9+10/10=10,然后10%10=0,这三个数变成2,10,0,再一次就是2+10/10=3,10%10=0,三个数变为3,0,0,而这正是我们要求的结果,在实际操作中,我们习惯于将数倒着存放,即将数存为10,9,2,这是为了进位方便,因为如果正序的话如果最高位发生进位我们就要将每一个数向后移动一位从而挪出一个空位,想想都麻烦,倒序的话因为是向后进位,想怎么进就怎么进

代码:

  

#include<iostream>
using namespace std;
int num[100];
int main()
{
	string s1,s2;
	cin>>s1>>s2;
	int len1=s1.length();
	int len2=s2.length();
	int i,j;
	//数位相乘 
	for(i=0;i<len1;i++)
	for(j=0;j<len2;j++)
	{
	   num[len1-1+len2-1-i-j]=num[len1-1+len2-1-i-j]+(s1[i]-'0')*(s2[j]-'0');	
	} 
	//进位
	for(i=0;i<len1+len2;i++)
	{
		num[i+1]=num[i+1]+num[i]/10;
		num[i]=num[i]%10;
	} 
	//寻找不为零的最高位
	for(i=len1+len2-1;i>=0;i--)
	{
		if(num[i]!=0)
		{
			break;
		}
	}
	//转换成字符串
	string result=""; 
	for(;i>=0;i--)
	{
		result=result+(char)(num[i]+'0');//一定要强制转换成字符 
	} 
	cout<<result<<endl;
   return 0;	
} 


 

猜你喜欢

转载自blog.csdn.net/daoshen1314/article/details/88178758
今日推荐