【LeetCode】67. 二进制求和
1 问题
给你两个二进制字符串 a 和 b ,以二进制字符串的形式返回它们的和。
示例 1:
输入:a = “11”, b = “1”
输出:“100”
示例 2:
输入:a = “1010”, b = “1011”
输出:“10101”
2 答案
自己写的,先转成十进制,再求和,再转成二进制
class Solution:
def addBinary(self, a: str, b: str) -> str:
int_a, int_b = 0, 0
c = ''
for i in range(len(a)):
int_a = int_a + int(a[i]) * 2 ** (len(a)-i-1)
for j in range(len(b)):
int_b = int_b + int(b[j]) * 2 ** (len(b)-j-1)
int_c = int_a + int_b
if int_c==0 : return "0"
while int_c:
c = str(int_c % 2) + c
int_c //= 2
return c
官方解
- 一行写法
class Solution:
def addBinary(self, a: str, b: str) -> str:
return bin(int(a, 2) + int(b, 2))[2:]
# int(a, 2) 将二进制字符串转成整数
# bin 将整数转换为二进制
# 对结果如"0b100"进行切片,去掉前面的’0b‘
- 二进制两数相加
class Solution:
def addBinary(self, a: str, b: str) -> str:
res, p = '', 0
d = len(b) - len(a)
a = '0'*d + a # 让a和b长度相同,如果d小于零,则不会补0
b = '0'*-d + b
for i, j in zip(a[::-1],b[::-1]): # 翻转切片,从后往前加
s = int(i) + int(j) + p # 二进制两数相加
res = str(s%2) + res
p = s // 2
return str(p)+res if p else res
https://leetcode.cn/problems/add-binary/solutions/7221/python-1xing-nei-zhi-han-shu-fei-nei-zhi-jie-fa-by/
- 也可以使用 divmod
class Solution:
def addBinary(self, a: str, b: str) -> str:
res, carry = '', 0
i = len(a) - 1
j = len(b) - 1
while i>=0 or j>=0 or carry:
tmp1 = int(a[i]) if i>=0 else 0
tmp2 = int(b[j]) if j>=0 else 0
carry, t = divmod(tmp1+tmp2+carry, 2) # carry除以2的商,t为余数
res = str(t) + res
i -= 1
j -= 1
return res
https://leetcode.cn/problems/add-binary/solutions/6200/mo-ni-guo-cheng-by-powcai-4/