67. Add Binary
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”
Constraints:
Each string consists only of ‘0’ or ‘1’ characters.
1 <= a.length, b.length <= 10^4
Each string is either “0” or doesn’t contain any leading zero.
解题思路:
bin()函数 – 返回一个整数 int 或者长整数 long int 的二进制表示。
返回的数值是以0b开头,表明返回的数值是二进制
int() 函数用于将一个字符串或数字转换为整型。
class int(x, base=10)
x – 字符串或数字。
base – 进制数,默认十进制。(指定base为非十进制时,x 需以字符串形式传入)
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
print(bin(int(a,2)+int(b,2)))
return bin(int(a,2)+int(b,2))[2:]
请多多指教。
文章标题:67. Add Binary
本文作者:顺强
发布时间:2020-05-12, 23:59:00
原始链接:http://shunqiang.ml/leetcode-67-add-binary/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。