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.  

       

  • 相关阅读:
    第十一节 jQuery特殊效果
    第十节 使用index和一个点击事件实现选项卡
    synchronized和lock两种锁的比较
    常见的四种线程池和区别
    mybatis中的#和$的区别
    web 防止SQL注入
    GIT配置免密登录
    热点 Key 问题的发现与解决
    Redis缓存击穿
    面试必问之JVM原理
  • 原文地址:https://www.cnblogs.com/prmlab/p/6895229.html
Copyright © 2011-2022 走看看