zoukankan      html  css  js  c++  java
  • 67. Add Binary

    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.  

       

  • 相关阅读:
    在单向链表中删除指定的key
    双向链表反转
    单向链表反转
    认识异或运算
    二分查找
    插入排序
    冒泡排序
    选择排序
    go 语言环境安装
    欧几里得算法
  • 原文地址:https://www.cnblogs.com/prmlab/p/6895229.html
Copyright © 2011-2022 走看看