看代碼吧~
1
2
3
4
5
6
7
8
9
10
11
|
dec = input ( '10進制數為:' ) print ( "轉換為二進制為:" , bin (dec)) print ( "轉換為八進制為:" , oct (dec)) print ( "轉換為十六進制為:" , hex (dec)) string1 = '101010' print ( '二進制字符串轉換成十進制數為:' , int (string1, 2 )) string1 = '367' print ( '八進制字符串轉換成十進制數為:' , int (string1, 8 )) string3 = 'FFF' print ( '十六進制字符串轉換成十進制數為:' , int (string1, 16 )) |
leetcode第476題:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Solution: def findComplement( self , num): """ :type num: int :rtype: int """ string = bin (num) string1 = '' for i in range ( 2 , len (string)): if string[i] = = '1' : string1 + = '0' else : string1 + = '1' return int (string1, 2 ) #二進制字符串轉換成10進制整數 |
python各進制之間轉換函數
這兩天在研究修正農歷庫的事情,搞的很累,想用代碼自動完成,于是又把python撿起來了,python還是很好撿的,雖然丟了挺長時間。
其中就用了python各進制轉換的問題,寫下來以,備忘。之所以要寫下來,而不是轉發,是因為很多人寫的比較啰嗦,我只把重點寫出來就可以了,其他全部去掉。
一共用到四個函數:bin()、oct()、int()、hex()
int():轉換為10進制;語法:Int(字符串,字符串進制) 。例: int("f",16) 輸出為15;int('11',2)輸出為3
即以下三個函數都是把10進制數轉換成目標進制。
bin():轉換為2進制;例:bin( int("f",16) )輸出:'0b1111' .bin(15)同樣輸出'0b1111'。
oct():轉換為8進制;
hex():轉換為16進制。
bin()、oct()、hex()的返回值均為字符串,分別帶有0b、0o、0x前綴,后續處理時需注意。
以下的x必須為“字符串”,需用引號。
2->8:oct(int(x, 2))
8->2:bin(int(x, 8))
2->16:hex(int(x, 2))
16->2:bin(int(x, 16))
其他用法一樣,就不舉例了。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/dxcve/article/details/81153331