首页 > 其他 > 详细

leetcode67. 二进制求和 🌟

时间:2019-07-13 00:53:54      阅读:112      评论:0      收藏:0      [点我收藏+]

题目:

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

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

示例 1:

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

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

来源:力扣(LeetCode)

解答:

1 class Solution:
2     def addBinary(self, a: str, b: str) -> str:
3         return bin(int(a, 2) + int(b, 2))[2:]
 1 class Solution:
 2     """
 3         作者:QQqun902025048
 4         链接:https://leetcode-cn.com/problems/two-sum/solution/python-1xing-nei-zhi-han-shu-fei-nei-zhi-jie-fa-by/
 5     """
 6     def addBinary(self, a: str, b: str) -> str:
 7         r, p = ‘‘, 0
 8         d = len(b) - len(a)
 9         a = 0 * d + a
10         b = 0 * -d + b   # ‘0‘ * -d = ‘‘
11         for i, j in zip(a[::-1], b[::-1]):
12             s = int(i) + int(j) + p
13             r = str(s % 2) + r
14             p = s // 2
15         return 1 + r if p else r

 1 class Solution:
 2     def addBinary(self, a: str, b: str) -> str:
 3         _sum = ‘‘
 4         c = 0
 5         d = len(a) - len(b)
 6         a = 0 * -d + a
 7         b = 0 * d + b
 8         for i in range(len(a) - 1, -1, -1):
 9             s = int(a[i]) + int(b[i]) + c
10             if s == 2:
11                 s = 0
12                 c = 1
13             elif s == 3:
14                 s = 1
15                 c = 1
16             else:
17                 c = 0
18             _sum = str(s) + _sum
19         
20         if c == 1:
21             _sum = 1 + _sum
22         return _sum

 

leetcode67. 二进制求和 🌟

原文:https://www.cnblogs.com/catyuang/p/11178837.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!