https://leetcode-cn.com/problems/add-binary/description/
python下的進制轉換 python
這是最快的:code
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ num=int(a,2)+int(b,2) ans=bin(num) return ans[2:]
順便記錄一下python下各種轉換,能夠看到直接用format這種轉換完了不用二次處理orm
# -*- coding: UTF-8 -*- printdec =19 print("十進制數爲:", dec) print("轉換爲二進制爲:", bin(dec)) print("轉換爲八進制爲:", oct(dec)) print("轉換爲十六進制爲:", hex(dec)) print("轉換爲二進制爲:", format(dec, 'b')) print("轉換爲八進制爲:", format(dec, 'o')) print("轉換爲十六進制爲:", format(dec, 'x'))
如下是輸出,能夠看到format後的結果不用二次處理blog
十進制數爲: 19 轉換爲二進制爲: 0b10011 轉換爲八進制爲: 0o23 轉換爲十六進制爲: 0x13 轉換爲二進制爲: 10011 轉換爲八進制爲: 23 轉換爲十六進制爲: 13
將其餘進制轉回十進制ip
print(int('10011',2)) print(int('23',8)) print(int('13',16))
看到個更牛逼的
leetcode
format(int(a, 2) + int(b, 2), "b")