zoukankan      html  css  js  c++  java
  • LeetCode 43. 字符串相乘

    43. 字符串相乘

    Difficulty: 中等

    给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

    示例 1:

    输入: num1 = "2", num2 = "3"
    输出: "6"
    

    示例 2:

    输入: num1 = "123", num2 = "456"
    输出: "56088"
    

    说明:

    1. num1 和 num2 的长度小于110。
    2. num1 和 num2 只包含数字 0-9
    3. num1 和 num2 均不以零开头,除非是数字 0 本身。
    4. 不能使用任何标准库的大数类型(比如 BigInteger)直接将输入转换为整数来处理

    Solution

    num1[i] * num2[j] will be placed at indices [i + j, i + j + 1]

    参考:Easiest JAVA Solution with Graph Explanation - LeetCode Discuss

    class Solution:
        def multiply(self, num1: str, num2: str) -> str:
            m, n = len(num1), len(num2)
            pos = [0] * (m + n)
            
            for i in range(m-1, -1, -1):
                for j in range(n-1, -1, -1):
                    mul = int(num1[i]) * int(num2[j])
                    p1 = i + j
                    p2 = i + j + 1
                    s = mul + pos[p2]
                    pos[p1] += s // 10
                    pos[p2]  = s % 10
            res = ''
            for p in pos:
                if p == 0 and not res:
                    continue
                else:
                    res += str(p)
            return res if res else "0"
    
  • 相关阅读:
    python数据类型以及模块的含义
    python基础语言以及if/while语句结构
    subprocess模块
    linux 管道通信socket 全双工示例
    整体框架
    licode_WebrtcConnection
    webrtc杂谈(转)
    修改背景颜色
    激活NX窗口的按钮
    NX屏蔽窗口的按钮
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14583295.html
Copyright © 2011-2022 走看看