码迷,mamicode.com
首页 > 其他好文 > 详细

#Leetcode# 43. Multiply Strings

时间:2018-11-23 20:43:27      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:res   als   ==   tor   rect   ack   bsp   note   span   

https://leetcode.com/problems/multiply-strings/

 

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

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contain only digits 0-9.
  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

代码:

class Solution {
public:
    string multiply(string num1, string num2) {
        string res;
        int n1 = num1.size(), n2 = num2.size();
        int k = n1 + n2 - 2, carry = 0;
        vector<int> v(n1 + n2, 0);
        for (int i = 0; i < n1; ++i) {
            for (int j = 0; j < n2; ++j) 
                v[k - i - j] += (num1[i] - ‘0‘) * (num2[j] - ‘0‘);
        }
        for (int i = 0; i < n1 + n2; ++i) {
            v[i] += carry;
            carry = v[i] / 10;
            v[i] %= 10;
        }
        int i = n1 + n2 - 1;
        while (v[i] == 0) --i;
        if (i < 0) return "0";
        while (i >= 0) res.push_back(v[i--] + ‘0‘);
        return res;
    }
};

 大数乘法

#Leetcode# 43. Multiply Strings

标签:res   als   ==   tor   rect   ack   bsp   note   span   

原文地址:https://www.cnblogs.com/zlrrrr/p/10009257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!