Bull Math(C语言)

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

模拟加法和乘法即可。

#include<stdio.h>
#include<string.h>
int main()
{
	char str[50], str2[50];
	scanf("%s", str);//以字符串形式输入两个整数
	scanf("%s", str2);
	int num[300], sum[3000];
	int len = strlen(str);//求出两个整数的位数
	int len2 = strlen(str2);
	int i, j, k, l, p = 0, q = len2, c, s;
	memset(num, 0, sizeof(num));//将两个数组初始化
	memset(sum, 0, sizeof(sum));
	for (i = len - 1; i >= 0; i--)//模拟乘法
	{
		c = 0, k = 0;
		for (j = len2 - 1; j >= 0; j--)//计算str的任意一位与str2每一位相乘的结果
		{
			s = (str[i] - '0') * (str2[j] - '0') + c;
			num[k] = s % 10;
			c = s / 10;
			k++;
		}
		int flat = 0;
		if (c > 0)//如果最后多进一位,将多的一位存入数组并标记
		{
			num[k] = c;
			flat = 1;
		}
		int n = 0;
		k = 0;
		for (l = p; l < q + flat; l++)//模拟加法,将所有乘积错位并相加
		{
			int x = sum[l];
			sum[l] = (sum[l] + num[k] + n) % 10;
			n = (num[k] + x + n) / 10;
			k++;
		}
		if (n > 0)//如果相加多进一位将其存入数组
			sum[l] = n;
		p++, q++;//将两个数之间错位
	}
	for (j = 2999; j >= 0; j--)//去掉所有前导零
		if (sum[j])
			break;
	for (i = j; i >= 0; i--)//将其输出
		printf("%d", sum[i]);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值