uva 10106 Product
The Problem
The problem is to multiply two integers X, Y. (0<=X,Y<10250)
The Input
The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.
The Output
For each input pair of lines the output line should consist one integer the product.
Sample Input
12 12 2 222222222222222222222222
Sample Output
144 444444444444444444444444
题目大意:两个数求积。
解题思路:高精度乘法,要注意因子为0的时候,思想跟高精度加法差不多。
#include<stdio.h>
#include<string.h>
int main() {
int c = 0;
char s1[1000], s2[1000];
char a[1000], b[1000];
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
while (gets(a) != NULL && gets(b) != NULL) {
int temp[1000] = {0};
memset(s1, 0, sizeof(s1));
memset(s2, 0, sizeof(s2));
int len = strlen(a);
for (int i = len - 1, j = 0; i >= 0; i--, j++) {
s1[j] = a[i];
}
int len2 = strlen(b);
for (int i = len2 - 1, j = 0; i >= 0; i--, j++) {
s2[j] = b[i];
}
memset(b, 0, sizeof(b));
if (strlen(s1) < strlen(s2)) {
strcpy(b, s1);
strcpy(s1, s2);
strcpy(s2, b);
}
int l1 = strlen(s1), l2 =strlen(s2);
for (int i = 0; i < l2; i++) {
for (int j = 0; j < l1; j++) {
temp[l1 - i - 1 + l2 - j - 1] += (s1[j] - '0') * (s2[i] - '0');
}
}
int temp2[1000] = {0};
for (int i = 0; i < l1 + l2 - 1; i++) {
temp2[i] = temp[l1 + l2 - 2 - i];
}
for (int i = 0; i < l1 + l2 - 1; i++) {
if (temp2[i] > 9) {
temp2[i + 1] += temp2[i] / 10;
temp2[i] %= 10;
}
}
int i, flag = 1, cnt = 0;
for (i = l1 + l2; i >= 0; i--) {
if (temp2[i] == 0 && flag) continue;
else flag = 0;
printf("%d", temp2[i]);
cnt++;
}
if (cnt == 0) {
printf("0");
}
printf("\n");
}
return 0;
}