题目:二进制求和
给定两个二进制字符串,返回他们的和(用二进制表示)。输入为非空字符串且只包含数字 1 和 0。
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.
示例:
输入: a = "11", b = "1", 输出: "100"
输入: a = "1010", b = "1011", 输出: "10101"
--------------------------------------------------------------
解法:通过 bin() 函数 直接转换,注意,转换的结果为带有 "0b" 字头的二进制字符串,需要去掉
bin() 返回一个整数 int 或者长整数 long int 的二进制表示。
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a, b = int(a, 2), int(b, 2)
# "0b" 是二进制数的标志,返回时需要通过切片[2:]去掉
# "0b100"
return bin(a+b)[2:]
参考:
https://www.runoob.com/python/python-func-bin.html