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;	
} 


 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ksuper&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值