新浪笔试:大数相乘.

来源:互联网 发布:mac淘宝买软件 编辑:程序博客网 时间:2024/06/08 08:14

这是一道新浪的笔试题,计算两个很大的数相乘并输出结果.思路是采取分解两个大数,将它们写成(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());}

这里写图片描述

0 0
原创粉丝点击