拼多多内推笔试二:数字字符串两个字符串相乘/大数相乘

这是四道笔试题的第二题:

两个字符串形式的数字,求相乘结果并保存到字符串,结果可能会很长,所以只能用字符串模拟乘法操作。

1、c+++代码如下:

#include <iostream>
#include <cstdio>
#include <string>  
#include <vector> 
#include <sstream>
using namespace std;
string multiply(string num1, string num2) {
    int l = num1.length();
    int r = num2.length();
    vector<int> num(l+r,0);
    for(int i=0;i<l;i++)
    {
        int n1=num1[l-1-i]-'0';
        int tmp=0;
        for(int j=0;j<r;j++)
        {
            int n2=num2[r-1-j]-'0';
            tmp=tmp+num[i+j]+n1*n2;
            num[i+j]=tmp%10;
            tmp/=10;
        }
        num[i+r]=tmp;
    }
    int k=l+r-1;
    while(k>0&&num[k]==0)k--;
    string result="";
    while(k>=0)result+=static_cast<char>('0'+num[k--]);
    return result;
}
int main(){
    string org;
     getline(cin,org);  
      istringstream iss(org);
      string a;
      string b;
      iss>> a >> b;
      cout<<multiply(a,b)<<endl;
     return 0;

参考的链接:
http://www.cnblogs.com/xinyuyuanm/archive/2013/04/26/3045598.html
牛客上的牛人解答:
https://www.nowcoder.com/discuss/30697?type=0&order=0&pos=17&page=2
https://www.nowcoder.com/discuss/30693?type=0&order=0&pos=25&page=1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值