确定比特的组合 [英] Determining combination of bits

查看:63
本文介绍了确定比特的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个类似下面的词典


{1:''one'',2:''two'',4:''three'',8: ''四'',16:''五'等等......}
我给了一些数字,比如22,25和9.我想确定

键,2的幂,包含数字。


Ex。 22 = 16 + 4 + 2

25 = 16 + 8 + 1

9 = 8 + 1

....等等.. 。


如何获得这些密钥?

Say I have a dictionary like the following

{1:''one'',2:''two'',4:''three'',8:''four'',16:''five'', etc...}

and I am given some numbers, say 22, 25, and 9. I want to determine the
keys, powers of 2, that comprise the number.

Ex. 22 = 16+4+2
25 = 16+8+1
9 = 8+1
....etc...

How do I get these keys?

推荐答案

Sean Berry< sean< at> buildingonline.com>写道:
Sean Berry <sean <at> buildingonline.com> writes:

我想确定包含数字的密钥,2的幂。

Ex。 22 = 16 + 4 + 2
25 = 16 + 8 + 1
9 = 8 + 1
......等等......

I want to determine the keys, powers of 2, that comprise the number.

Ex. 22 = 16+4+2
25 = 16+8+1
9 = 8+1
...etc...




这听起来像家庭作业,所以我只想在这里给出一个提示:



This sounds suspiciously like a homework, so I''m just going to give a hint here:

导入数学
math.log(22,2)
4.4594316186372973 2 ** int(math.log(22,2))
16 2 ** int(math.log(22) - 16,2))
4 2 ** int(math.log(22 - 16 - 4 - 2,2))
2
import math
math.log(22, 2) 4.4594316186372973 2**int(math.log(22, 2)) 16 2**int(math.log(22 - 16, 2)) 4 2**int(math.log(22 - 16 - 4 - 2, 2)) 2




希望这是有帮助的。


史蒂夫



Hope this is helpful.

Steve


你没有'没有说明

数字有多大。如果它们保持较小(例如<数千)

你可以直接从字典中查找它们。

如果它们可以任意大,你必须使用bit

shifing和boolean& (和)。


听起来很像家庭作业,但我会给你一些提示。


1)使用位移运算符(>>)和布尔&

运算符来隔离整数中的每一位。


2)它将为零或一。建立一个

的清单,这些清单代表每一位代表两个人的b $ b。


Larry Bates


Sean Berry写道:
You didn''t say anything about how large the
numbers might get. If they stay small (e.g. <thousands)
you could just look them up directly from a dictionary.
If they can get arbitrarily large you must use bit
shifing and boolean & (and).

Sounds a lot like a homework assignment, but I''ll
give you some "hints".

1) Use bit shifting operator (>>) and boolean &
operator to isolate each bit in the integer.

2) It will be either zero or one. Build up a
list of these which will represent the power
of two that each one bit represents.

Larry Bates

Sean Berry wrote:
说我有一个类似下面的词典

{1:''one'',2: ''two'',4:''three'',8:''four'',16:''five''等......}

我给了一些数字,说22,25和9.我想确定构成数字的
键,2的幂。

Ex。 22 = 16 + 4 + 2
25 = 16 + 8 + 1
9 = 8 + 1
......等等......

我如何获得这些钥匙?
Say I have a dictionary like the following

{1:''one'',2:''two'',4:''three'',8:''four'',16:''five'', etc...}

and I am given some numbers, say 22, 25, and 9. I want to determine the
keys, powers of 2, that comprise the number.

Ex. 22 = 16+4+2
25 = 16+8+1
9 = 8+1
...etc...

How do I get these keys?





" Sean Berry" < SE ** @ buildingonline.com>在消息中写道

news:x3Qjd.121786

"Sean Berry" <se**@buildingonline.com> wrote in message
news:x3Qjd.121786


这篇关于确定比特的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆