zoukankan      html  css  js  c++  java
  • #Leetcode# 43. Multiply Strings

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

     大数乘法

  • 相关阅读:
    asp.net web生命周期
    图的数据结构1
    最长公共子串
    内部排序

    棋盘覆盖问题
    队列
    矩阵连乘问题
    图的数据结构2
    旅行售货员问题
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10009257.html
Copyright © 2011-2022 走看看