大数相乘算法

不能计算负数,小数。
用string对象存储数值,然后逆序排列,从左向右相乘进位。
[参考1](http://www.cnblogs.com/heyonggang/p/3599857.html)
[参考2](http://www.cnblogs.com/life91/p/3389890.html)
#include<iostream>
#include<string>
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值