
[英]How to get sum of numbers having exactly 2 one's in their binary representation in a range?
[英]How to get the numbers where the binary representation is 1?
我正在尝试在 python 中实现一些快速的二进制求幂。 我想知道数字的二进制表示返回1的整数。也许一个例子会更清楚:
bin(13) # returns 1101 because one 8 + one 4 + one 1 = 13.
如何构建返回 8,4,1 的 function 并将二进制数作为参数传递? 正如你所看到的,我并没有明确地试图获得 2 的幂,而是将幂相乘的极简表示。
这个问题有点令人困惑(见我的评论),但我还是想分享一个解决方案,因为目前接受的答案对我来说似乎令人困惑。 出于好奇,我明天可能会比较和基准测试一堆不同的解决方案。
bin_num = bin(13)
def bin_str_decomp(bin_num_str):
bin_clean = bin_num_str[:1:-1]
return [1 << idx for idx, bit in enumerate(bin_clean) if bit == '1']
print(bin_str_decomp(bin_num))
您可以单独执行以下操作:
# Split the binary and grab interested part, and its size.
# >> bin(123456789) == "0b111010110111100110100010101"
binary = bin(123456789)[2:]
size = len(binary)
numbers = []
for i in range(size):
# Checks to see if the binary[i] is not equals to zero.
if binary[i] is not "0":
# Indexes the `binary` string and adds (size - i - 1) zeros to the end of it.
number = int(binary[i] + "0" * (size - i - 1), 2)
numbers.append(number)
print(numbers)
# >> [67108864, 33554432, 16777216, 4194304, 1048576, 524288, 131072, 65536, 32768, 16384, 2048, 1024, 256, 16, 4, 1]
这是一个较短的解决方案。
binary = bin(13)[2:]
nums = [
int(binary[i] + "0" * (len(binary) - i - 1), 2)
for i in range(len(binary))
if binary[i] is not "0"
]
return nums
这是单行解决方案,也是如此。
print((lambda binary: [int(binary[i] + "0" * (len(binary) - i - 1), 2) for i in range(len(binary)) if binary[i] is not "0"])(binary = bin(123456789)[2:]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.