LeetCode小白菜笔记[16]:Add Binary

LeetCode小白菜笔记[16]:Add Binary

67. Add Binary [easy]

题目:

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

For example,
a = "11"
b = "1"
Return "100".

两个表示二进制数的string相加,结果用string返回,code 如下:

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        carry = 0
        summ = ''
        if len(a) > len(b):
            lg = a
            st = b
        else:
            lg = b
            st = a
        for i in range(1,len(lg)+1):
            if i <= len(st):
                summ = str(int(lg[-i]) ^ int(st[-i]) ^ carry) + summ
                carry = int(int(lg[-i]) + int(st[-i]) + carry > 1)
            else:
                if i <= len(lg):
                    summ = str(int(lg[-i]) ^ carry) + summ
                    carry = int(int(lg[-i]) + carry > 1)
        if carry == 0:
            return summ
        else:
            return '1' + summ

先把指针分别指向长序列和短序列,在两个序列都有值的时候,每个位用ai+bi+carry,在只有一个有值的时候,用ai+carry,ai是长序列的元素。最后返回的时候看看有没有carry,有的话就要添一个‘1’,没有就直接返回。

62ms,14.46%

discuss上看到了一个有意思的:

class Solution:
    def addBinary(self, a, b):
        return bin(eval('0b' + a) + eval('0b' + b))[2:]

巧妙的用了类型转换函数bin,把求和出来的整数转成binary的字符串输出,求和过程直接用了eval转换成10进制。不过感觉有点过度利用python内置的函数了。。。比较实用,但是不知道作为算法题的答案是否合适。

另外,python中的异或实用^这个冒尖表示的,不是xor。需要注意。

2018年2月9日23:52:56

快十二点了呀~

原文地址:https://www.cnblogs.com/morikokyuro/p/13256813.html