Example: product of 9876543210 * 1234567890
Analysis: the normal data structure can no longer meet the result of such a large number multiplication. Only arrays can be used for operations.
1. Both numbers are received by character array.
2. After receiving, because each bit is multiplied by each bit of another number,
The position of array subscript 0 is the highest position of the number, so that the highest change will occur after each multiplication. The position of subscript 0 is not easy to change.
You need to transfer the lowest value to the position where the subscript is 0, and change the highest array subscript to the maximum subscript.
So, we need to reverse the original two numbers.
3. Multiplication of two numbers. In the process of multiplying each bit, it is possible that the product is greater than 10, and carry is required. Therefore, to judge whether the product after multiplication is greater than 10, if it is greater than 10, carry is required.
Each carry and multiplication needs to be added with the value of the original subscript position to obtain the final value
4. Before output, it is necessary to determine the number of digits. From the back to the front, when the character 0 is encountered, it is assigned as' \ 0 ', and the string ends with 0.
5. Because the product is reversed, the output needs to be reversed again. Just print this number in reverse.
1 #include <iostream>
2 using namespace std;
3 int main() {
4 char a[100], b[100], c[100] = {0};
5 int i, j, k, l, A, B, C;
6 //Enter first number
7 cin >> a;
8 //View the length of the first number
9 for (i = 0; a[i] != '\0';++i) { }
10 A = i;
11 //Reverse the first number and position
12 for (i = 0; i <= (A - 1) / 2;++i) {
13 k = a[i];
14 a[i] = a[A - i - 1];
15 a[A - i - 1] = k;
16 }
17 //Enter the second number
18 cin >> b;
19 //View the length of the second number
20 for (i = 0; b[i] != '\0';++i) {}
21 B = i;
22 //Reverse the second number and position
23 for (i = 0; i <= (B - 1) / 2;++i) {
24 k = b[i];
25 b[i] = b[B - i - 1];
26 b[B - i - 1] = k;
27 }
28 //Multiplication of two numbers
29 for (i = 0; i <= A - 1;++i) {
30 for (j = 0; j <= B - 1;++j) {
31 C=(a[i]-48) * (b[j]-48);
32 k = i + j;
33 c[k] = c[k] + C;
34 C = c[k];
35 for (l = 0; c[k + l] >= 10;++l) {
36 c[k+l] = c[k + l] % 10;
37 c[k + l + 1] = C / 10 + c[k + l+1];
38 C = c[k+l+1];
39 }
40 }
41 }
42
43 //Output multiplied number
44 for (i = 19; c[i] == 0;i--) {
45 if (c[i]==0) {
46 c[i] = '\0';
47 }
48 }
49 j = i + 1;
50 for (i = 0; i < (j - 1)/2;++i) {
51 k = c[i];
52 c[i] = c[j-i - 1];
53 c[j - i - 1] = k;
54 }
55 for (i = 0; i < j;++i) {
56 printf("%d",c[i]);
57 }
58 }