# POJ 2389 Bull Math C++版

POJ题解 1440浏览

Description

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

Slyar:就是高精度乘法，这次我尝试了直接把结果保存到字符串里返回，继续试验了不少字符串函数，很爽。注意结果里的前导0要去掉。过不去的试试 20 50 这个数据，或许会有收获，我在这WA了2次…

```#include
#include
#include

using namespace std;

string bignum(string& a, string& b)
{
int i, j, k;
int sum[81] = {0};
string c;

/* 一位一位算乘法 */
for (i = a.length() - 1; i >= 0; i--)
{
for (j = b.length() - 1; j >= 0; j--)
{
sum[i + j] += (a[i] - '0') * (b[j] - '0');
}
}

/* 处理进位 */
for (i = a.length() - 1; i >= 0; i--)
{
for (j = b.length() - 1; j >= 0; j--)
{
if (i + j == 0) break;
sum[i + j - 1] += sum[i + j] / 10;
sum[i + j] %= 10;
}
}

/* 将数组转换为字符串 */
for (i = 0; i < a.length() + b.length() - 1; i++)
{
if (sum[i] / 10)
{
c.append(1, (sum[i] / 10) + '0');
c.append(1, (sum[i] % 10) + '0');
}
else
{
c.append(1, sum[i] + '0');
}
}

/* 去掉前导0 */
c.erase(0, c.find_first_not_of('0'));
if(c.empty()) c = "0";

return c;
}

int main()
{
int si, ci;
string a, b, c;
cin >> a >> b;

c = bignum(a, b);

cout << c << endl;

//system("pause");
return 0;
}
```