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

    Problem statement:

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

    Note:

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

    Solution:

    This problem is a math related question. The following figures give a very brief explanation about how to match the digits multiplication to the final result.

    We should loop from the back of two strings, this pattern follows the multiplication rules. Suppose the two digits form num1 is i and num2 is j, the final position in multiplication is i + j and i + j + 1. We need to update the mul[i + j + 1] by addition and mul[i + j + 1] by carry.

    We should think carefully about the corner case.

    1. leading zero.
    2. For the test case, such as "999", "0", if we ignore the leading zero, the return string is "". When return value, do this test.

    Time complexity is O(m * n).

    class Solution {
    public:
        string multiply(string num1, string num2) {
            string mul_str;
            vector<int> mul(num1.size() + num2.size(), 0);
            for(int i = num1.size() - 1; i >= 0; i--){
                for(int j = num2.size() - 1; j >= 0; j--){
                    int dig_mul = (num1[i] - '0') * (num2[j] - '0') + mul[i + j + 1];
                    mul[i + j + 1] = dig_mul % 10;
                    mul[i + j] += dig_mul / 10;
                }
            }
            for(auto digit : mul){
                if(!(digit == 0 && mul_str.empty())) {
                    mul_str.push_back(digit + '0');
                }
            }
            return mul_str.empty() ? "0" : mul_str;
        }
    };
  • 相关阅读:
    正则表达式分组替换注意
    L2 正则化的直观理解
    git版本控制
    callbacks
    validation_data作用
    pandas 对某一列添加过滤
    py-redis 设置过期时间
    什么情况下要做预算会计
    超过一年的一个营业周期是什么意思?
    无形资产为什么属于非流动资产
  • 原文地址:https://www.cnblogs.com/wdw828/p/6876896.html
Copyright © 2011-2022 走看看