LeetCode--Python解析【Add Binary】(67)

题目:

方法:

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        len_a = len(a) - 1
        len_b = len(b) - 1
        num_a = 0
        num_b = 0
        for i in a:
            num_a += (2**len_a) * int(i)
            len_a -= 1
        for i in b:
            num_b += (2**len_b) * int(i)
            len_b -= 1        
        num = num_a + num_b

        return bin(num)[2:]
        

手写了二进制转十进制的代码

十进制转二进制用了python内置的函数

附上python进制转换函数:

转十进制:dec() 

转二进制:bin()

转八进制:oct()

转十六进制:hex()

猜你喜欢

转载自blog.csdn.net/ZJRN1027/article/details/81221855