Premiumlab  

https://leetcode.com/problems/add-binary/#/description

 

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

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

 

 

Solution:

 

We will use recursion to solve this problem. First, we get last digit of the two numbers, a and b, and then if the last digits are 1 and 1, then we need to carry. We will call the addBinary method on the digits before the last digit, and then append 0 to the sum of two binary numbers. However, if the last digits are 0,0 or 0, 1, then we do not to carry. And we will recursively call the method on the previous digits and append 0 or 1 to the last digit of the sum.  

 

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        if len(a) == 0:
            return b
        if len(b) == 0:
            return a
        if a[-1] == '1' and b[-1] == '1':
            return self.addBinary(self.addBinary(a[:-1], b[:-1]), '1') + '0'
        if a[-1] == '0' and b[-1] == '0':
            return self.addBinary(a[:-1], b[:-1]) + '0'
        else:
            return self.addBinary(a[:-1], b[:-1]) + '1'

 

Note :

 

1. a[:-1] means get everything before the last element. Supper useful in digit retrival, espeacially the digits of number are unknown. Forget about the mod function, ugh. 

ex.

a = [1,2,3,4,5]

a[:-1] 

 

 

[1,2,3,4]

 

2. Edge check. 

 

3. def in the class defines a METHOD not a FUNCTION. Do use the self.nameofmethod(...) when calling the method recursively. 

 

ex.

class Solution:

    def addBinary(self, a, b):

        XXXXXXX

        XXXXXXX

        XXXXXXX    self.addBinary(a,b)   # no need to include self in the parentheses. 

        XXXXXXX    

 

 

 

 

4. Python syntax: 

 

if XXXXXXX:

    XXXXXXX

if XXXXXXX:

    XXXXXXX    

else: # not elif

    XXXXXXX      

 

 

5. Use single quotes to quote numbers/strings.....

It is okay to add '1'/'0' at the end of or in the front of numbers, on bit manipulation.  

 

   

posted on 2017-05-23 17:48  Premiumlab  阅读(111)  评论(0编辑  收藏  举报