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;
        }
    };
  • 相关阅读:
    IT学习 程序员 学习网址收藏
    PHP地图上的点文字标注
    php 三种文件下载的实现
    10个免费的jQuery富文本编辑器
    Docker Swarm(四)Volume 数据(挂载)持久化
    Docker Swarm(三)Service(服务)分配策略
    Docker Swarm(二)常用命令
    Docker Swarm(一)集群部署
    Linux——Shell脚本参数传递的2种方法
    Linux——系统时间、开机时间
  • 原文地址:https://www.cnblogs.com/wdw828/p/6876896.html
Copyright © 2011-2022 走看看