日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode算法入门- Multiply Strings -day18

發布時間:2025/3/12 编程问答 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode算法入门- Multiply Strings -day18 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

LeetCode算法入門- Multiply Strings -day18

  • 題目介紹
  • Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

    Example 1:

    Input: num1 = “2”, num2 = “3”
    Output: “6”

    Example 2:

    Input: num1 = “123”, num2 = “456”
    Output: “56088”

    Note:

    The length of both num1 and num2 is < 110.
    Both num1 and num2 contain only digits 0-9.
    Both num1 and num2 do not contain any leading zero, except the number 0 itself.
    You must not use any built-in BigInteger library or convert the inputs to integer directly.

  • 題目分析
    解題思想在于這個圖:
  • 通過上述的推導我們可以發現num1[i] * num2[j]的結果將被保存到 [i + j, i + j + 1] 這兩個索引的位置。其中它們的個位數保存在 (i + j + 1) 的位置,十位數保存在 (i + j) 的位置。所以我們可以定義一個數組 pos[m + n] ,它的長度為兩個數組的長度。只是它們的計算不需要把它們給反轉過來。每次我們有num1[i] * num2[j]的時候先取得 pos1 = i + j, pos2 = i + j + 1。這樣得到的值是
    sum = num1[i] * num2[j] + pos[pos2]。按照前面的計算規則,。pos[pos1] = pos[pos1] + sum/10; pos[pos2] = sum % 10;

  • Java實現
  • class Solution {public String multiply(String num1, String num2) {int m = num1.length();int n = num2.length();//定義這個數組來存儲最后結果的每一位int[] pos = new int[m+n];//從最右邊開始,所以是m-1for(int i = m -1; i >= 0; i--){for(int j = n -1; j >= 0; j--){int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');int p1 = i + j;int p2 = i + j + 1;//這里進行運算,最后需要用到的是數組每個下標的值,下面不是很理解int sum = mul + pos[p2];pos[p1] = pos[p1] + sum/10;pos[p2] = sum % 10;}}StringBuilder sb = new StringBuilder();for(int p : pos){//排除高位數為0的情況if(sb.length() == 0 && p == 0){continue;}else{sb.append(p);}}//排除長度為0的情況if(sb.length() == 0)return "0";else{return sb.toString();}} } 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

    總結

    以上是生活随笔為你收集整理的LeetCode算法入门- Multiply Strings -day18的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。