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"
最简单的想法就是用python自带函数将二进制字符串转为十进制数字,相加后再返回二进制。
把二进制字符串转为十进制有很多方法,这个比较常用。int(str,2)
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
numa = int(a,2)
numb = int(b,2)
return bin(numa+numb)[2:]
本文介绍了一种使用Python内置函数解决二进制字符串相加问题的方法。通过将二进制字符串转换为十进制数,进行数值相加后,再转换回二进制字符串输出。示例代码展示了如何实现这一过程。
1016

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



