zoukankan      html  css  js  c++  java
  • leetcode67. 二进制求和 🌟

    题目:

      给定两个二进制字符串,返回他们的和(用二进制表示)。

      输入为非空字符串且只包含数字 1 和 0。

    示例 1:

      输入: a = "11", b = "1"
      输出: "100"
    示例 2:

      输入: a = "1010", b = "1011"
      输出: "10101"

    来源:力扣(LeetCode)

    解答:

    class Solution:
        def addBinary(self, a: str, b: str) -> str:
            return bin(int(a, 2) + int(b, 2))[2:]
    View Code
    class Solution:
         """
             作者:QQqun902025048
             链接:https://leetcode-cn.com/problems/two-sum/solution/python-1xing-nei-zhi-han-shu-fei-nei-zhi-jie-fa-by/
         """
         def addBinary(self, a: str, b: str) -> str:
             r, p = '', 0
             d = len(b) - len(a)
             a = '0' * d + a
             b = '0' * -d + b   # '0' * -d = ''
             for i, j in zip(a[::-1], b[::-1]):
                 s = int(i) + int(j) + p
                 r = str(s % 2) + r
                 p = s // 2
             return '1' + r if p else r
    View Code
    class Solution:
        def addBinary(self, a: str, b: str) -> str:
            _sum = ''
            c = 0
            d = len(a) - len(b)
            a = '0' * -d + a
            b = '0' * d + b
            for i in range(len(a) - 1, -1, -1):
                s = int(a[i]) + int(b[i]) + c
                if s == 2:
                    s = 0
                    c = 1
                elif s == 3:
                    s = 1
                    c = 1
                else:
                    c = 0
                _sum = str(s) + _sum
            
            if c == 1:
                _sum = '1' + _sum
            return _sum
    View Code
  • 相关阅读:
    ASP.NET Core 静态资源的打包与压缩
    算法
    字符串反转
    js 获取随机数
    AspNetCore MVC 跨域
    add digits
    1-bit and 2-bit Characters
    删除字符串中出现次数最少的字符
    洗牌
    哈夫曼编码
  • 原文地址:https://www.cnblogs.com/catyuang/p/11178837.html
Copyright © 2011-2022 走看看