31/300
67.二进制求和
给定两个二进制字符串,返回他们的和(用二进制表示)。
nbsp;
输入为非空字符串且只包含数字 1 和 0。
nbsp;
示例 1:
nbsp;
输入: a = “11”, b = “1”
输出: “100”
nbsp;
示例 2:
nbsp;
输入: a = “1010”, b = “1011”
输出: “10101”
二进制转十进制,大概印象是除以2然后留余数。
十进制转二进制,好像是2的几次方乘以1/0然后加一起。
偷懒:
python有int( , base= 10)
,默认十进制
int( , base= 2)
就是把原先的二进制变成十进制
bin()
是变成二进制,但结果有个’0b’在前面,要删了
class Solution:
def addBinary(self, a: str, b: str) -> str:
return bin(int(a,2) + int(b,2))[2:]
非内置函数解决办法:
True + True = 2
False + True = True + False = 1
False + False = 0
class Solution:
def addBinary(self, a: str, b: str) -> str:
res, carry = '', 0
i, j = len(a)-1, len(b)-1
while i>=0 or j>=0 or carry:
tmp = (i>=0 and a[i]=='1') + (j>=0 and b[j]=='1')
carry, rem = divmod(tmp + carry, 2)
res = str(rem) + res
i-=1; j-=1
return res