原题
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = “11”, b = “1”
Output: “100”
Example 2:
Input: a = “1010”, b = “1011”
Output: “10101”
解法
先使用int()函数将a, b转化为整数, 再整数相加后用bin()转化为二进制, 取’0b’之后的数字部分.
代码
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2) + int(b, 2))[2:]
本文介绍了一种解决二进制字符串相加问题的方法。通过将输入的二进制字符串转换为整数,进行整数相加后再转换回二进制字符串。此方法适用于处理非空且只包含1或0的输入字符串。
7604

被折叠的 条评论
为什么被折叠?



