本文介紹了不使用內(nèi)置 bin 函數(shù)將整數(shù)轉(zhuǎn)換為二進(jìn)制的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
此函數(shù)接收一個(gè)整數(shù)作為參數(shù),并應(yīng)返回一個(gè)列表,該列表表示以二進(jìn)制表示的相同值作為位列表,其中列表中的第一個(gè)元素是最高有效(最左邊)位.
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.
我的函數(shù)當(dāng)前為數(shù)字 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]
這篇關(guān)于不使用內(nèi)置 bin 函數(shù)將整數(shù)轉(zhuǎn)換為二進(jìn)制的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!