[leetcode:python]67.Add Binary

来源:互联网 发布:决战武林进阶数据地煞 编辑:程序博客网 时间:2024/04/29 15:46

题目:
Given two binary strings, return their sum (also a binary string).

For example,
a = “11”
b = “1”
Return “100”.

方法一:性能72ms

class Solution(object):    def addBinary(self, a, b):        """        :type a: str        :type b: str        :rtype: str        """        r = 0        for i in range(len(a)):            r += pow(2, i)*int(a[len(a)-i-1])        for i in range(len(b)):            r += pow(2, i)*int(b[len(b)-i-1])        s = '{0:b}'.format(r)        return s

方法二:性能38ms

class Solution(object):    def addBinary(self, a, b):        """        :type a: str        :type b: str        :rtype: str        """        return bin(int(a, 2) + int(b,2))[2:]

这里int(a, 2)表示a是二进制数,将它转换成十进制数。

1 0
原创粉丝点击