LeetCode:Multiply Strings

原创 2016年05月30日 11:49:31

Multiply Strings




Total Accepted: 62981 Total Submissions: 265241 Difficulty: Medium

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.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

Subscribe to see which companies asked this question

Hide Tags
 Math String



















思路:

如:num1="123",num2="45";对应结果存储在ans[num1.size()+num2.size()]中。

从右到左对位相乘,只要确定相乘后的结果在ans中位置即可。

参考讨论区的图:



即:num1[i] * num2[j]相乘后的对应位置为:i+j和i+j+1。


c++ code:

class Solution {
public:
    string multiply(string num1, string num2) {
        
        int len1 = num1.size(),len2 = num2.size();
        
        string ans(len1+len2,'0');
        
        for(int i=len1-1;i>=0;i--) {
            for(int j=len2-1;j>=0;j--) {
                
                int mul = (num1[i]-'0') * (num2[j]-'0');
                int p1 = i + j;
                int p2 = p1 + 1;
                int sum = mul + ans[p2]-'0';
                ans[p2] = sum % 10 + '0';
                ans[p1] += sum / 10; // 这里ans[p1]-'0',而sum/10+'0',因此抵消
            }
        }
        
        // 去掉前面的0
        int start  = 0;
        while(ans[start]=='0') start++;
        ans = ans.substr(start);
        
        return ans.size()==0 ? "0" : ans;
        
    }
};


版权声明:本文为博主原创文章,转载请注明出处。

LeetCode OJ算法题(四十二):Multiply Strings

题目: Given two numbers represented as strings, return multiplication of the numbers as a string....
  • op_yu
  • op_yu
  • 2014年08月01日 14:44
  • 274

LeetCode (19) Multiply Strings

题目描述Given two numbers represented as strings, return multiplication of the numbers as a string.Note:...

LeetCode(43)Multiply Strings

题目Given two numbers represented as strings, return multiplication of the numbers as a string.Note: T...
  • fly_yr
  • fly_yr
  • 2015年08月28日 17:42
  • 3082

leetcode - 43.Multiply Strings

Multiply Strings

leetCode_Multiply Strings(大位数相乘)

题意:两个大位数的乘法(用String实现) 思路:很简单,模拟人的乘法即可。这道题印象很深刻,因为我小学最初学编程,学到最后就是这个题。但是我当时太不踏实了,就没静下心来学。等到本科想编这道题,发现...

Leetcode 43 - Multiply Strings(高精度乘)

题意实现高精度乘法。思路模拟即可,但是模拟也是有方法的。算法1直接像我们手算乘法一样模拟,每次计算出来的一位都要保证小于10并且记录进位。过程如下:算法2比算法1简单很多。还是像手算乘法一样,但是比如...
  • Lzedo
  • Lzedo
  • 2017年03月16日 08:02
  • 170

LeetCode | Multiply Strings

题目: Given two numbers represented as strings, return multiplication of the numbers as a string. N...

[C++]LeetCode: 69 Multiply Strings

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

LeetCode 043 Multiply Strings

题目 ...
  • seawade
  • seawade
  • 2015年03月26日 16:23
  • 224

LeetCode OJ-43-Multiply Strings

题目:Given two numbers represented as strings, return multiplication of the numbers as a string. Note...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode:Multiply Strings
举报原因:
原因补充:

(最多只允许输入30个字)