Codewars第三天–Binary Addition
题目描述:
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.
The binary number returned should be a string.
该题就是一个简单的把两个数的和以二进制的形式输出。可以直接使用python3
中的bin()
函数就可以实现十进制到底二进制的转换了。但是这个函数输出的结果最前端含有0b
字符表示二进制,因此需要把他们去掉,可以用之前使用过的replace()
就可以了。代码如下:
def add_binary(a,b):
#your code here
sum = bin(a + b)
sum = sum.replace('0b', '')
return sum