问题:
输入两个整数, 求其和,并将其转换为二进制输出(字符串);
例:
输入:3,4
输出:“111”
Python的递归实现:
def add_binary(a,b):
input = a + b
out = binary_0(input) # 返回输入值的二进制字符串
# 将返回的字符串翻转
l = list(out)
l.reverse()
result = "".join(l)
print(result)
return(a)
def binary_0(input, output=""):
# 生成二进制字符串
if (input != 0):
a = input % 2
output = output + str(a)
return binary_0(int(input / 2), output) # 递归调用
else:
return output
# 调用该函数
add_binary(1, 2046)
输出结果为:
11111111111
Process finished with exit code 0