Description
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.
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
Example
Example 1:
Input: a = “11”, b = “1”
Output: “100”
Example 2:
Input: a = “1010”, b = “1011”
Output: “10101”
Submissions
首先这道题是将二进制数a和b相加并输出,因此解题思路用到了int()和bin()方法。
int() 用于将一个字符串或数字转换为整型。如:class int(x, base=10),其中参数x 指字符串或数字,base 指进制数,默认十进制。
bin() 返回一个整数 int 或者长整数 long int 的二进制表示。如:bin(x),其中参数x 指 int 或者 long int 数字。且bin()输出的结果前面会有0b标识,因此解题时使用[2:]去除了前两位输出。
实现代码如下:
class Solution:
def addBinary(self, a: str, b: str) -> str:
return bin(int(a,2)+int(b,2))[2:]