43. Multiply Strings

来源:互联网 发布:linux操作系统原理 编辑:程序博客网 时间:2024/06/05 02:39
题目要求:

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
题目要求得到两个以字符串表示的正数的积,但是不能直接将字符串转为整数。相当于模拟整数乘法。从低位开始遍历,将被乘数逐位与被乘数相乘,并储存进位。将所得的积依次相加,最后将得到的数组转为字符串。

代码如下:

string multiply(string num1, string num2)      {          int m = num1.size(), n = num2.size();          if(m == 0 || n == 0) return 0;          string res(m + n, '0');            reverse(num1.begin(), num1.end());          reverse(num2.begin(), num2.end());            for(int i = 0; i < m; ++i)          {              int r = 0;              for(int j = 0; j < n; ++j)              {                  int tmp = (res[i + j] - '0') + (num1[i] - '0') * (num2[j] - '0') + r;                  res[i + j] = tmp % 10 + '0';                  r = tmp / 10;              }              res[i + n] += r;          }            reverse(res.begin(), res.end());            size_t pos = res.find_first_not_of("0");          if(pos != string::npos)          {              return res.substr(pos);          }            return "0";      }  


0 0
原创粉丝点击