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