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

    Description: Given two binary strings a and b, return their sum as a binary string.

    Link: 67. Add Binary

    Examples:

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

    思路: 二进制加法,先把a, b补齐,长度相同,短的前面补0,这样就不用后面还要判断。进位carry。

    class Solution(object):
        def addBinary(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            m, n = len(a), len(b)
            if m < n:
                a = "0"*(n-m)+a
            else:
                b = "0"*(m-n)+b
            a, b = list(a), list(b)
            res, carry = "", 0
            while a and b:
                cur = int(a.pop()) + int(b.pop()) + carry
                if cur >= 2:
                    carry = 1
                    cur = cur % 2
                else:
                    carry = 0
                res = str(cur) + res
            if carry == 1:
                res = "1" + res
            return res

    日期: 2021-04-25 是周日啊,阴天,今天晨跑完好累

  • 相关阅读:
    8.02_python_lx_day14
    8.02_python_lx_day13<2>
    8.02_python_lx_day13<1>
    7.30_python_lx_day20
    7.29_python_lx_da19
    7.29_python_lx_day12
    Docker镜像
    Docker学习Ⅱ
    Docker学习Ⅰ
    2-3树的插入和删除原理
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14699239.html
Copyright © 2011-2022 走看看