LeetCode:Multiply Strings

来源:互联网 发布:blast算法 编辑:程序博客网 时间:2024/05/19 17:26

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
Hide Similar Problems
 (M) Add Two Numbers (E) Plus One (E) Add Binary



















思路:

如: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;            }};


0 0
原创粉丝点击