版权声明:随意取用(´・ω・`) / https://blog.csdn.net/square_zou/article/details/84146039
Problem
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = “11”, b = “1”
输出: “100”
示例 2:
输入: a = “1010”, b = “1011”
输出: “10101”
too young 思路-40ms
先转成整数,再转回去。。。
class Solution(object):
def addBinary(self, a, b):
sa = str(a)
sb = str(b)
numa = numb = 0
for i in range(len(sa)):
numa += int(sa[i]) * pow(2, len(sa)-i-1)
for i in range(len(sb)):
numb += int(sb[i]) * pow(2, len(sb)-i-1)
return bin(numa+numb)[2:]
dalao 思路-20ms
竟然一行解决,绝了
#20ms
class Solution(object):
def addBinary(self, a, b):
return bin(int(a,2)+int(b,2))[2:]
还有另一种版本
#28ms
class Solution(object):
def addBinary(self, a, b):
#eval二进制转十进制
return bin(eval('0b'+a)+eval('0b'+b))[2:]