题目描述:

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形式,非负,只含数字,长度小于110,没有前导零)的积,返回值同样是string形式。

解题思路:

我的想法是:先把num2中个、十、百……位上的数依次乘num1,然后用一个数组nums把这些数值个位对个位、十位对十位……相加存储起来,最后将得到的数组(因为里面有的数大于10,所以不是两个数的积)转化为答案。

我的代码:

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         string ret = "";
 5         int n1 = num1.length(), n2 = num2.length(), index = 0;
 6         vector<int> nums(n1+n2,0);
 7         for(int i = n1-1; i >= 0; i--){
 8         //第一步和第二步
 9             int carry = 0;//进位
10             for(int j = n2-1; j >= 0; j--){
11                 int t = (num1[i]-'0')*(num2[j]-'0')+carry;
12                 carry = t/10;
13                 nums[index++]+= t%10;
14             }
15             nums[index]=carry;//可能还会有一个进位
16             index = n1-i;//对应 i 所在的位置(个位、十位……)
17         }
18         for(int i = 0; i < n1+n2; i++){
19         //第三步
20             ret = (char)(nums[i]%10+'0')+ret;
21             nums[i+1]+= nums[i]/10;
22         }
23         while(ret[0]=='0'&&ret.length()>1)
24         //因为第三步转化时把nums里面所有数都转了,所以要把多余的0去掉
25             ret.erase(ret.begin());
26         return ret;
27     }
28 };

 

他人代码:

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {        
 4     //我省了第二步num1各个位与num2的所有积的和的进位,这段代码连第一步num1各个位与num2的积的进位也省了.666,仔细想想num1,num2位对位求完积之后先进位,再求所有积的和,再进位,顺序调换下只要求一次进位,陷入思维定式了。   
 5         string s;
 6         int i, j, n1=num1.size(), n2=num2.size();
 7         vector<int> res(n1+n2, 0);
 8         for (i=0; i<n1; i++)
 9             for (j=0; j<n2; j++) {
10                 res[n1+n2-i-j-2]+=(num1[i]-'0')*(num2[j]-'0');
11             }
12         for (i=0; i<n1+n2-1; i++)
13             res[i+1]+=res[i]/10, res[i]%=10;
14         while (!res[i] && i>0)
15             i--;       
16         for (; i>=0; i--)
17             s+=(char)('0'+res[i]);
18         return s;
19     }
20 };

 

 

 

posted on 2018-03-01 22:17  宵夜在哪  阅读(82)  评论(0编辑  收藏  举报