↓快轉到主要內容
  1. LeetCode/

LeetCode 415: Add Strings

·1 分鐘· ·
LeetCode Easy Math String Simulation
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-24

  • 提交紀錄:Runtime Error ×4 → Wrong Answer ×2 → Accepted

解題思路
#

直式加法(Math 模板六):i、j 從兩個字串的尾巴往前,比較短的那個走完就當成 0。每一位 total = a + b + carry,寫下 total % 10,進位是 total // 10。迴圈結束時如果還有進位,要再補一位。最後把結果反轉。

我的嘗試
#

這題提交了 7 次:

  • 第一版語法錯誤,接著寫成 i = j = len(num1) - 1, len(num2) - 1,兩個變數都變成同一個 tuple(TypeError);之後兩版忘了把字元轉成 int。
  • 修好之後忘了最後的進位:"8" + "6" 回傳 "4"。下一版補的是 total 而不是進位 temp,回傳 "44"。改成補 temp 就 AC 了。

正確解法
#

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        i, j, carry = len(num1) - 1, len(num2) - 1, 0
        res = []
        while i >= 0 or j >= 0 or carry:
            a = int(num1[i]) if i >= 0 else 0
            b = int(num2[j]) if j >= 0 else 0
            carry, d = divmod(a + b + carry, 10)
            res.append(str(d))
            i, j = i - 1, j - 1
        return "".join(reversed(res))

複雜度
#

時間 O(max(n, m)),空間 O(max(n, m))。

要特別避免的錯誤
#

  • 最後的進位要補上:"8" + "6" 是 "14"。
  • 補的是進位 carry,不是最後一位的 total。
  • i = j = a, b 會讓兩個變數都變成 tuple。

面試口說整理
#

我用兩個指標從尾巴往前逐位相加,短的那邊走完就當成 0,記錄進位,把進位也放進迴圈條件,這樣最後的進位不會漏掉,最後把結果反轉。時間 O(max(n, m))。

相關文章

LeetCode 412: Fizz Buzz
·1 分鐘
LeetCode Easy Math String Simulation
LeetCode 412 解題筆記:先判斷 15 的倍數,再判斷 5 和 3;倍數要用 %,不是 //
LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 405: Convert a Number to Hexadecimal
·1 分鐘
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 解題筆記:負數先加上 2^32 變成補數,再每次取 4 個位元(% 16)轉成十六進位;0 要特別處理
LeetCode 258: Add Digits
·1 分鐘
LeetCode Easy Math Simulation Number-Theory
LeetCode 258 解題筆記:反覆把位數相加直到剩一位;O(1) 解法是 digital root:1 + (n - 1) % 9
LeetCode 171: Excel Sheet Column Number
·1 分鐘
LeetCode Easy Math String
LeetCode 171 解題筆記:從左到右 res = res × 26 + 字母的值(A = 1)
LeetCode 168: Excel Sheet Column Title
·1 分鐘
LeetCode Easy Math String
LeetCode 168 解題筆記:Excel 欄名是沒有 0 的 26 進位,每一位用 (n - 1) % 26 取字母,再 n = (n - 1) // 26