题目:
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 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
原文:https://www.cnblogs.com/catyuang/p/11178837.html