新浪笔试:大数相乘.

这是一道新浪的笔试题,计算两个很大的数相乘并输出结果.思路是采取分解两个大数,将它们写成(a1*10^n1 + a2*10^n2…..)*(b1*10^n1 + b2*10^n2…..)的形式,然后计算a1b1,a2b2…,然后加上权重,最后加起来.算法的时间界是(N1*N2/M^2),N1,N2是输入的位数.

#include "iostream"
#include  "string"
#include "vector"
#include "algorithm"
#include "memory"
#include "set"
using namespace std;

const int M = 6;//每次用来计算的数据
void add(string & ans,  string temp);
int  main()
{

    string x, y;
    cout << "please enter two interger:\n";
    while (cin >> x >> y)
    {
        string ans(x.size()+y.size()+1,'0');
        string sub_x, sub_y;
        size_t pos_x = 0;//标记子串的位置
        while (pos_x < x.size())
        {
            sub_x = x.substr(pos_x, M);
            size_t pos_y = 0;
            while (pos_y < y.size())
            {
                sub_y = y.substr(pos_y, M);
                size_t weight = x.size()-pos_x-sub_x.size()+y.size()-pos_y-sub_y.size();//定义这一次子串的权重
                long long temp_result = stod(sub_x)*stod(sub_y);
                if (temp_result)
                add(ans, to_string(temp_result)+string(weight,'0'));//与结果累加
                pos_y += M;
            }
            pos_x += M;
        }
        cout<<endl<<string(ans.find_first_not_of('0') + ans.begin(), ans.end());
    } 
    return 0;
}
void add(string & ans,  string temp)
{
    reverse(ans.begin(), ans.end());//反转
    reverse(temp.begin(), temp.end());
    size_t c = 0;//进位
    for (size_t i = temp.find_first_not_of('0'); i != temp.size(); ++i)//循环计算每一位的加法
    {
        size_t bit_ans = c + temp[i] + (0 - '0') + ans[i] +(0 - '0');
        c = bit_ans / 10;//得到新进位
        ans[i] = bit_ans - c*10 + ('0'-0);//得到该位的值,char
    }

    for (size_t i = temp.size(); c!=0; ++i)
    {
        size_t bit_ans = ans[i]+(0-'0') + c;//得到该位的值,char
        c = bit_ans / 10;
        ans[i] = bit_ans - c*10 + ('0' - 0);//得到该位的值,char
    }
    reverse(ans.begin(), ans.end());
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值