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;
        }
    };
  • 相关阅读:
    C语言中的复合类型
    C语言中的函数与指针
    C语言中的循环结构与选择结构
    C语言中的运算符
    C语言中的变量
    毕业论文查重网站
    Protocol and Delegate协议和代理
    NSArray与NSMutableArray 数组与可变数组
    UI复习
    NSString方法与NSMutableString方法
  • 原文地址:https://www.cnblogs.com/wdw828/p/6876896.html
Copyright © 2011-2022 走看看