大数相乘算法

不能计算负数,小数。
用string对象存储数值,然后逆序排列,从左向右相乘进位。
[参考1](http://www.cnblogs.com/heyonggang/p/3599857.html)
[参考2](http://www.cnblogs.com/life91/p/3389890.html)
#include
#include
void fan(std::string & str);
std::string multiply(std::string & v1, std::string & v2);

int main()
{
    using namespace std;
    string v1;
    string v2;
    string mul;

    cout << "Enter the first number: ";
    cin >> v1;
    cout << "Enter the next number: ";
    cin >> v2;

    mul = multiply(v1, v2);
    cout << v1 << " x " << v2 << " = " << mul;

    return 0;
}

void fan(std::string & str)
{
    char temp = '0';
    int start = 0;
    int end = str.size() - 1;
    while (start < end)
    {
        temp = str[start];
        str[start++] = str[end];
        str[end--] = temp;
    }
}

std::string multiply(std::string & v1, std::string & v2)
{
    fan(v1);
    fan(v2);

    std::string temp(v1.size() + v2.size() + 1, '0');
    unsigned int t = 0;

    for (int i = 0; i < v1.size(); i++)
    {
        unsigned int j;
        for (j = 0; j < v2.size(); j++)
        {
            t += temp[i + j] - '0' + (v1[i] - '0' )* (v2[j] - '0');
            temp[i + j] = (t % 10) + '0';
            t = t / 10;
        }
        while (t)
        {
            temp[i + j++] += t % 10;
            t = t / 10;
        }
    }

    for (int i = temp.size() - 1; i >= 0; i--)
    {
        if (temp[i] != '0')
            break;
        else
            temp.pop_back();
    }
    fan(temp);
    fan(v1);
    fan(v2);
    return temp;
}

你可能感兴趣的:(算法,C++,大数相乘,数据结构)