leetcode 67 二进制求和
问题描述
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例1:
输入: a = "11", b = "1"
输出: "100"
示例2:
输入: a = "1010", b = "1011"
输出: "10101"
解题思路:
老老实实的采用了较为暴力的列举法来作答,所以代码较为复杂,且可读性较差
class Solution:
def addBinary(self, a: str, b: str) -> str:
res = int(a) + int(b)
res = list(str(res))[::-1]
for i in range(len(res)):
res[i] = int(res[i])
if res[i] == 1:
res[i] = '1'
if res[i] == 2:
if i == len(res)-1:
res[i] = '0'
res.append('1')
else:
res[i] = '0'
res[i+1] = str(int(res[i+1])+1)
elif int(res[i]) > 2:
if i == len(res)-1:
res[i] = '1'
res.append('1')
else:
res[i] = '1'
res[i+1] = str(int(res[i+1])+1)
else:
res[i] = str(res[i])
return ''.join(res[::-1])
在评论区有更简单的做法,但是是用到了Python原生的二进制相关函数:
class Solution:
def addBinary(self, a, b):
a = int(a, 2)
b = int(b, 2)
result = a + b
return bin(result)[2:]