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;
總結
以上是生活随笔為你收集整理的LeetCode算法入门- Multiply Strings -day18的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言如何输入矩阵_如何在 COMSOL
- 下一篇: 史上最容易理解————GET和POST两