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.  

       

  • 相关阅读:
    update语句
    java List和数组相互转换方法
    mysql查最大字符串
    Mybatis各种模糊查询
    mysql 递归查询父节点 和子节点
    String类型根据逗号分隔转为list
    This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its de 错误解决办法
    java中String数组和List的互相转化
    实现List集合中数据逆序排列
    String字符串去掉双引号
  • 原文地址:https://www.cnblogs.com/prmlab/p/6895229.html
Copyright © 2011-2022 走看看