LeetCode Multiply Strings 大数相乘

题目要求:

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

代码: 

代码支持 大负数的相乘

class Solution {
public:
  string multiply(string num1, string num2) 
  {
    int flag1 = 1, flag2 = 1;
    if(num1.empty() || num2.empty())
      return " ";
    if(num1[0] == '-')
      flag1 = -1;
    if(num2[0] == '-')
      flag2 = -1;
    string res;
    if(num1[0] == '0' || num2[0] == '0')
      return "0";
    int len = num1.size();
    if(flag1 == -1)
      num1 = num1.substr(1);
    if(flag2 == -1)
      num2 = num2.substr(1);
    for(int i = num1.size() - 1; i >= 0; --i)
    {
      MultiplyByNum(res, num2, num1[i], len - i - 1);
    }
    if(flag1 != flag2)
      res.insert(res.begin(), '-');
    return res;
  }
  
  void MultiplyByNum(string& res, const string& multi, 
                     char num, int multiply)
  {
    string tmp;
    if(num == '0')
      return;
    MultiplyByNum(tmp, multi, num);
    for(size_t i = 0; i < multiply; ++i)
      tmp.push_back('0');
    Add(res, tmp);
  }
  void MultiplyByNum(string& res, const string& multi, char num)
  {
    int carry = 0;
    for(int i = multi.size() - 1; i >= 0; --i)
    {
      int tmp = (multi[i] - '0') * (num - '0') + carry;
      res.push_back((tmp % 10) + '0');
      carry = tmp / 10;
    }
    if(carry != 0)
      res.push_back(carry + '0');
    reverse(res.begin(), res.end());
  }
  
  void Add(string& num1, string& num2)
  {
    int carry = 0;
    string tmp;
    int len1 = num1.size(), len2 = num2.size();
    int i = len1 - 1, j = len2 - 1;
    while(i >= 0 || j >= 0)
    {
      int sum = 0;
      if(i >= 0)
      {
        sum += num1[i] - '0';
        --i;
      }
      if(j >= 0)
      {
        sum += num2[j] - '0';
        --j;
      }
      sum += carry;
      tmp.push_back((sum % 10) + '0');
      carry = sum / 10;
    }
    if(carry != 0)
      tmp.push_back(carry + '0');
    reverse(tmp.begin(), tmp.end());
    num1 = tmp;
  }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值