1. 程式人生 > >leetcode python 67. 二進位制求和

leetcode python 67. 二進位制求和

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        num1=num2=0
        z=0
        while(1):
            if len(a) == 0:
                break
            num1=num1+pow(2,z)*int(a[-1])
            a=a[:-1]
            z+=1
z = 0 while (1): if len(b) == 0: break num2 = num2 + pow(2, z) * int(b[-1]) b = b[:-1] z += 1 sum = num1+num2 sum = str(bin(sum)[2:]) return sum

這是最快的:

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下各類轉換

# -*- coding: UTF-8 -*-

# 獲取使用者輸入十進位制數
dec = int(input("輸入數字:"))

print("十進位制數為:", dec)
print("轉換為二進位制為:", bin(dec))
print
("轉換為八進位制為:", oct(dec)) print("轉換為十六進位制為:", hex(dec))