Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
def dec2binr(n): if n == 1: return '1' else: return (str(n%2)+dec2binr(n//2))[::-1]
没有 [::-1] 它返回反转的正确二进制数。[::-1] 在这种情况下不起作用 - 对于 n=40 Ii 得到:
011000
当我期望
101000
没有 [::-1] 我得到
000101
这是相反的,但正确的。为什么会发生这种情况,我该如何解决?
您需要反转附加字符串的方式。
return dec2binr(n//2) + str(n%2)
问题是,n%2将读取最低有效位,但您将其附加到字符串的左侧,这是最重要的位置。
n%2
之所以会发生这种情况,是因为您在每次 return时反转,将位弄乱了。从递归返回时不反转,或者仅在返回最终结果时反转(提示:辅助函数)。