Skip to content

Latest commit

 

History

History
53 lines (38 loc) · 1.14 KB

067._add_binary.md

File metadata and controls

53 lines (38 loc) · 1.14 KB

67. Add Binary

难度: Easy

刷题内容

原题连接

内容描述

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"
Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

解题方案

思路 1

几种case:

  • a or b 为空,最简单
  • 唯一的问题是如果有进位的处理,进位的处理就是先让其中的一个数和‘1’addBinary处理 ,然后再用addBinary
class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        if a == '' or b == '':
            return a + b
        if a[-1] == '0' and b[-1] == '0':
            return self.addBinary(a[:-1], b[:-1]) + '0'
        elif a[-1] == '1' and b[-1] == '1':
            return self.addBinary(a[:-1], self.addBinary(b[:-1], '1')) + '0'
        else:
            return self.addBinary(a[:-1], b[:-1]) + '1'