給定一個十進製數,將其轉換為二進製、八進製和十六進製數。這是將十進製轉換為二進製、十進製轉換為八進製、十進製轉換為十六進製的函數。
例子:
Input : 55 Output : 55 in Binary : 0b110111 55 in Octal : 0o67 55 in Hexadecimal : 0x37 Input : 282 Output : 282 in Binary : 0b100011010 282 in Octal : 0o432 282 in Hexadecimal : 0x11a
將十進製轉換為其他基數示例
一種解決方案是使用下麵帖子中討論的方法。 Convert from any base to decimal and vice versa Python 提供了用於標準基數轉換的直接函數,例如 bin()、hex() 和 oct()
PYTHON
# Python program to convert decimal to binary,
# octal and hexadecimal
# Function to convert decimal to binary
def decimal_to_binary(dec):
decimal = int(dec)
# Prints equivalent decimal
print(decimal, " in Binary : ", bin(decimal))
# Function to convert decimal to octal
def decimal_to_octal(dec):
decimal = int(dec)
# Prints equivalent decimal
print(decimal, "in Octal : ", oct(decimal))
# Function to convert decimal to hexadecimal
def decimal_to_hexadecimal(dec):
decimal = int(dec)
# Prints equivalent decimal
print(decimal, " in Hexadecimal : ", hex(decimal))
# Driver program
dec = 32
decimal_to_binary(dec)
decimal_to_octal(dec)
decimal_to_hexadecimal(dec)
輸出
(32, ' in Binary : ', '0b100000') (32, 'in Octal : ', '040') (32, ' in Hexadecimal : ', '0x20')
該程序的時間複雜度為 O(1),因為該程序僅由三個簡單函數組成,並且所有函數都隻打印值。該程序的空間複雜度也是 O(1),因為不需要額外的內存來存儲任何值。
使用字符串格式將十進製轉換為其他基數
我們可以使用字符串格式將十進製數轉換為其他基數。以下是如何使用字符串格式將十進製數轉換為二進製、八進製和十六進製的示例:
Python3
def convert_to_other_bases(decimal):
# Convert to binary
binary = "{0:b}".format(decimal)
# Convert to octal
octal = "{0:o}".format(decimal)
# Convert to hexadecimal
hexadecimal = "{0:x}".format(decimal)
# Print results
print(f"{decimal} in binary: {binary}")
print(f"{decimal} in octal: {octal}")
print(f"{decimal} in hexadecimal: {hexadecimal}")
convert_to_other_bases(55)
輸出
55 in binary: 110111 55 in octal: 67 55 in hexadecimal: 37
時間複雜度: O(1),因為代碼僅執行恒定數量的操作(格式化和打印結果)。
輔助空間: O(1) 作為代碼,僅創建一些不依賴於輸入大小(十進製數)的變量(二進製、八進製、十六進製)。
相關用法
- Python Decimal轉String用法及代碼示例
- Python Decimal轉Hexadecimal用法及代碼示例
- Python Decimal same_quantum()用法及代碼示例
- Python Decimal scaleb()用法及代碼示例
- Python Decimal shift()用法及代碼示例
- Python Decimal sqrt()用法及代碼示例
- Python Decimal to_eng_string()用法及代碼示例
- Python Decimal to_integral_exact()用法及代碼示例
- Python Decimal adjusted()用法及代碼示例
- Python Decimal as_tuple()用法及代碼示例
- Python Decimal canonical()用法及代碼示例
- Python Decimal compare()用法及代碼示例
- Python Decimal compare_signal()用法及代碼示例
- Python Decimal compare_total()用法及代碼示例
- Python Decimal compare_total_mag()用法及代碼示例
- Python Decimal conjugate()用法及代碼示例
- Python Decimal copy_abs()用法及代碼示例
- Python Decimal copy_negate()用法及代碼示例
- Python Decimal copy_sign()用法及代碼示例
- Python Decimal from_float()用法及代碼示例
- Python Decimal is_canonical()用法及代碼示例
- Python Decimal is_finite()用法及代碼示例
- Python Decimal is_infinite()用法及代碼示例
- Python Decimal is_nan()用法及代碼示例
- Python Decimal is_qnan()用法及代碼示例
注:本文由純淨天空篩選整理自佚名大神的英文原創作品 Convert Decimal to Other Bases in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。