Cynthia
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: 【LeetCode】0043. Multiply Strings date: 2018-12-26 is_modified: false disqus: cynthiahackmd categories: - "面試刷題" tags: - "LeetCode" --- {%hackmd @CynthiaChuang/Github-Page-Theme %} <br> Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. <!--more--> <br> **Example 1:** ```python Input: num1 = "2", num2 = "3" Output: "6" ``` **Example 2:** ```python Input: num1 = "123", num2 = "456" Output: "56088" ``` <br> > **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. <br> **Related Topics:** `String`、`Math` ## 解題邏輯與實作 這題最直接的解法是用直式乘法的方法做,嘿,就是下面的那個東西,小學算的要死要活的那個! ![enter image description here](https://slidesplayer.com/slide/11174206/60/images/26/%E7%9B%B4%E5%BC%8F%E4%B9%98%E6%B3%95%E7%9A%84%E6%A6%82%E5%BF%B5.jpg) <br> 直式乘法最基本的概念就是,按位相乘、位移相加,有這個概念就可以實作了,不過有幾點要先知道的: 1. m 位數與 n 位數相乘,結果最大為 m+n 位 2. n1[i] 與 n2[j] 相乘結果會出現在 answer[i+j]上 ← 忘了說,這條是因為我把乘數與被乘數反轉才成立的 3. **corner case** :任何與 0 相乘都會是 0 ,所以遇到是 0 可以直接回傳了 實做過程如下: 1. 判斷乘數與被乘數是否 0 ,若任一數為 0 ,則回傳答案為 0 ,否則繼續向下執行。 2. 反轉乘數與被乘數,方便從最低位數開始計算。 3. 使用雙層迴圈,依序取值,兩相乘後與進位值和上一層相乘結果相加。 4. 最後將計算結果反轉後回傳。 ```python= class Solution: def __init__(self): self.acrii_0 = ord('0') def chr_to_int(self,num): return ord(num) - self.acrii_0 def int_to_chr(self,num): return chr(num + self.acrii_0) def mult(self, num1, num2, carry): num1 = self.chr_to_int(num1) num2 = self.chr_to_int(num2) carry = self.chr_to_int(carry) result = num1 * num2 + carry carry = 0 if result >= 10 : carry = result // 10 result = result % 10 return self.int_to_chr(result), self.int_to_chr(carry) def add(self, num1, num2): num1 = self.chr_to_int(num1) num2 = self.chr_to_int(num2) result = num1+num2 return self.int_to_chr(result) def multiply(self, num1, num2): if num1 == "0" or num2 == "0": return "0" len_num1 = len(num1) len_num2 = len(num2) answer = [''] * (len_num1 + len_num2) num1 = num1[::-1] num2 = num2[::-1] for j in range(len_num2): for i in range(len_num1): n1 = num1[i] n2 = num2[j] carry = '0' if answer[i+j] == "" else answer[i+j] result, carry = self.mult(n1,n2,carry) answer[i+j] = result if carry != "0" : if answer[i+j+1] != "" : answer[i+j+1] = self.add(answer[i+j+1] ,carry) else: answer[i+j+1] = carry answer = answer[::-1] return "".join(answer) ``` 因為題目要求不能轉 int,但我又不想自己做相乘,所以我折中使用 arcii 的方法,算是有點偷吃步吧 XD ### 作弊... 上面那邊用自己做的乘法器,執行完的效果感覺不是很好,跑出了大約 536 ms、6.77% 的成績。想說要來就一下 40 ms 的寫法,看完之後我輸的不冤阿… ```python = class Solution: def multiply(self, num1, num2): return str(int(num1)*int(num2)) ``` 這位仁兄直接轉整數後相乘再轉回來,當然快... ## 其他連結 1. [【LeetCode】0000. 解題目錄](/x62skqpKStKMxRepJ6iqQQ) <br><br> > **本文作者**: 辛西亞.Cynthia > **本文連結**: [辛西亞的技能樹](https://cynthiachuang.github.io/LeetCode-0043-Multiply-Strings) / [hackmd 版本](https://hackmd.io/@CynthiaChuang/LeetCode-0043-Multiply-Strings) > **版權聲明**: 部落格中所有文章,均採用 [姓名標示-非商業性-相同方式分享 4.0 國際](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en) (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully