8.4 數字處理
504. Base 7
題目描述
給定一個十進制整數,求它在七進制下的表示。
輸入輸出範例
輸入一個整數,輸出一個字串,表示其七進制。
Input: 100
Output: "202"
在這個範例中,100 的七進制表示法來源於 100 = 2 * 49 + 0 * 7 + 2 * 1。
題解
進制轉換
類型的題目,通常是利用除法和取模(mod)來進行計算,同時也要注意一些細節,如負數和零。如果輸出是數字類型而非字串,也需要考慮是否會超出整數上下界。
- C++
- Python
string convertToBase7(int num) {
if (num == 0) {
return "0";
}
string base7;
bool is_negative = num < 0;
num = abs(num);
while (num) {
int quotient = num / 7, remainder = num % 7;
base7 = to_string(remainder) + base7;
num = quotient;
}
return is_negative ? "-" + base7 : base7;
}
def convertToBase7(num: int) -> str:
if num == 0:
return "0"
base7 = ""
is_negative = num < 0
num = abs(num)
while num:
quotient, remainder = num // 7, num % 7
base7 = str(remainder) + base7
num = quotient
return "-" + base7 if is_negative else base7
複雜度分析
- 時間複雜度:
- 每次將
num
除以7
,最多執行 次。
- 每次將
- 空間複雜度:
- 需要儲存
base7
字串,長度約為 。
- 需要儲存
172. Factorial Trailing Zeroes
題目描述
給定一個非負整數,判斷它的階乘結果的結尾有幾個 0。
輸入輸出範例
輸入一個非負整數,輸出一個非負整數,表示輸入的階乘結果的結尾有幾個 0。
Input: 12
Output: 2
在這個範例中,12! = 479001600 的結尾有兩個 0。