每天开心一点

Python:每日一题 92

2017-11-27 14:47:00    六月    644    来源: http://bbs.fishc.com/thread-95931-1-1.html

我们知道1,2,4,8,16,32,64和128这8个数字利用加法可以得到1~255中的任意数字,如
21 = 1 + 4 + 16
192 = 64 + 128
编写一个函数输入1~255的数字,给出如何用1,2,4,8,16,32,64和128 的加法可以到这个数字。
  1. def fun(num):
  2.     ........

  3. >>> print(fun(155))
  4. 1 + 2 + 8 + 16 + 128
  5. >>> print(fun(3))
  6. 1 + 2
  7. >>> print(fun(8))
  8. 8
复制代码


我的解法:

您是VIP用户,您可免回复查看本帖隐藏的内容

  1. def fun(num):
  2.     return ' + '.join([str(2**i) for i in range(len(bin(num)) - 2) if bin(num)[- i - 1] == '1'])


复制代码