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

LeetCode 504: Base 7

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

基本資料
#

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

  • 提交紀錄:Runtime Error → Accepted

解題思路
#

進位轉換(Math 模板七):對 abs(num) 一直取 % 7 得到最低位、// 7 往前,最後反轉,負數再補 -。num = 0 時迴圈不會執行,要直接回傳 "0"。

我的嘗試
#

第一次提交貼錯了題目,送出的是另一題(BST 的眾數)的程式碼(AttributeError)。十幾秒後換成正確的程式就 AC 了。

正確解法
#

class Solution:
    def convertToBase7(self, num: int) -> str:
        if num == 0:
            return "0"
        n, digits = abs(num), []
        while n:
            digits.append(str(n % 7))
            n //= 7
        return ("-" if num < 0 else "") + "".join(reversed(digits))

複雜度
#

時間 O(log n),空間 O(log n)。

要特別避免的錯誤
#

  • 0 要特別處理。
  • 對負數用絕對值做,Python 的 % 對負數會回傳正的餘數。

面試口說整理
#

我對絕對值一直取除以 7 的餘數得到每一位,整除後繼續,最後反轉並加上負號;0 直接回傳。時間 O(log n)。

相關文章

LeetCode 415: Add Strings
·1 分鐘
LeetCode Easy Math String Simulation
LeetCode 415 解題筆記:兩個指標從尾巴往前逐位相加,記錄進位,迴圈結束後還有進位要補上
LeetCode 405: Convert a Number to Hexadecimal
·1 分鐘
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 解題筆記:負數先加上 2^32 變成補數,再每次取 4 個位元(% 16)轉成十六進位;0 要特別處理
LeetCode 412: Fizz Buzz
·1 分鐘
LeetCode Easy Math String Simulation
LeetCode 412 解題筆記:先判斷 15 的倍數,再判斷 5 和 3;倍數要用 %,不是 //
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
LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2