LeetCode:Multiply Strings

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值