题目
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
一行代码实现:
def addBinary(self, a: str, b: str) -> str:
return bin(int(a,2)+int(b,2))[2:]
bin()方法
将十进制整数转成二进制输出
例如:
print(bin(666))
打印结果为:
0b1010011010
结果前面会用0b
标识,所以上述代码末尾使用切片[2:]
去除了
int()方法
def __init__(self, x, base=10): # known special case of int.__init__
"""
int(x=0) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
# (copied from class doc)
"""
描述
int函数可以将一个指定进制的数字型字符串或者十进制数字转化为整形。
语法
int (object, base)
名称 | 说明 | 备注 |
---|---|---|
object | 一个数字或字符串参数 | 数字参数可以是整数、浮点数(小数点表示和指数e表示皆可) 字符串参数仅能包含在指定进制下所涵盖的字符 该参数可省略 |
base | 进制数 | 该参数可省略,省略时默认为10 (正整型参数),表示object所对应的进制 |
二进制数转化为十进制数
test = ['111011011111', '0b101']
for number in test:
print(int(number, 2))
输出结果为:
3807
5
关于int()的其他用法我会单独出一篇进行讲解