Here is the simple example,but I think it's cheating.


  • 0
    W

    class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
    res=str(bin(int(a,2)+int(b,2)))
    return res[2:]


  • 0
    V

    If one need to demonstrate the understanding of data structures, the above implementation may not be a better way as it shows nothing about the understanding of adding element by element. In an interview one might probably be asked to implement the built in function bin. On an another note, the above way of solving might be cheating only if the interviewer thinks so.

      class Solution:
        def addBinary(self,a,b):
            reslen = max(len(a),len(b))
            a,b=a.rjust(reslen,'0')[::-1],b.rjust(reslen,'0')[::-1]
            carry,res=0,''
            for i in range(reslen):
                carry,num=divmod(int(a[i])+int(b[i])+carry,2)
                res+=str(num)
            if carry:
                res+='1'
            return res[::-1]

  • 0
    M
    class Solution:
        def addBinary(self, a, b):
            return '{0:b}'.format(int(a, 2) + int(b, 2))
    

    Why not crack it? :)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.