本文介紹了不使用內置 bin 函數將整數轉換為二進制的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
此函數接收一個整數作為參數,并應返回一個列表,該列表表示以二進制表示的相同值作為位列表,其中列表中的第一個元素是最高有效(最左邊)位.
This function receives as a parameter an integer and should return a list representing the same value expressed in binary as a list of bits, where the first element in the list is the most significant (leftmost) bit.
我的函數當前為數字 11 輸出 '1011'
,我需要 [1,0,1,1]
代替.
My function currently outputs '1011'
for the number 11, I need [1,0,1,1]
instead.
例如,
>>> convert_to_binary(11)
[1,0,1,1]
推薦答案
def trans(x):
if x == 0: return [0]
bit = []
while x:
bit.append(x % 2)
x >>= 1
return bit[::-1]
這篇關于不使用內置 bin 函數將整數轉換為二進制的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!