生成长度为 n 且 1 和 0 数量相同的二进制数
问题与标题相同。 我已经做了两种方法。一是直截了当。 生成所有位掩码
2^{n-1}
到
2^n
并且对于每个位掩码检查是否有相同数量的 1 和 0,如果是,则对其进行处理。 这就是问题所在,因为我必须处理这些位掩码,而不仅仅是计算它们。
我采用了第二种方法,该方法运行时间为 O(2^{n/2}) ,但似乎它没有生成所有位掩码,我不知道为什么。
第二种方法是这样的: 生成从 0 到 2^{n/2} 的所有位掩码并具有有效的位掩码(称为 B )我必须执行以下操作: B#~B
其中 ~ 为负数。
例如我有 n=6,所以我将生成长度为 3 的位掩码。
例如我有 B=101,所以 ~B 将是 010 最终的位掩码将是 101010,正如我们所看到的,我们有相同数量的 1 和 0。
这个方法好还是我实施的方法不好?也许存在另一种有趣的方法? 谢谢克里斯
Question same as in the title.
I've done two approaches. One is straightforward.
Generate all bitmasks from
2^{n-1}
to
2^n
And for every bitmask check if there is same amount 1's and 0's, if yes, work on it.
And that's the problem, because i have to work on those bitmasks not only count them.
I came with second approach which runs on O(2^{n/2}) time, but seems like it's not generating all bitmasks and i don't know why.
Second approach is like that :
generate all bitmasks from 0 to 2^{n/2} and to have valid bitmask( call it B ) i have to do something like this : B#~B
where ~ is negative.
So for example i have n=6, so i'm going to generate bitmasks with length of 3.
For example i have B=101, so ~B will be 010
and final bitmask would be 101010, as we see, we have same amount of 1's and 0's.
Is this method good or am i implementing something bad ? Maybe some another interesting approach exist?
Thanks
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试递归方法:
调用
printMasks
并向其传递所需数量的 0 和 1。例如,如果您需要 3 个 1 和 3 个 0,请这样调用:Try a recursive approach:
Call
printMasks
passing it the desired number of 0's and 1's. For example, if you need 3 ones and 3 zeros, call it like this:给定一个二进制数,可以通过对足够大以容纳所有位的字使用恒定数量的操作来生成具有相同数量“1”的下一个更高的二进制数(假设除以两个计数的幂)作为一项操作)。
确定最不重要的“1”的位置(提示:如果递减数字会发生什么)和上面最不重要的“0”(提示:如果将“最不重要的 1”添加到原始数字会发生什么?)您应该将最低有效位“0”更改为“1”,并将适当数量的最低有效位设置为“1”,并将中间位设置为“0”。
It's possible, given a binary number, to produce the next higher binary number which has the same number of 'ones', using a constant number of operations on words large enough to hold all the bits (assuming that division by a power of two counts as one operation).
Identify the positions of the least significant '1' (hint: what happens if you decrement the number) and the least significant '0' above that (hint: what happens if you add the "least significant 1" to the original number?) You should change that least significant '0' to a '1', and set the proper number of least-significant bits to '1', and set the intervening bits to '0'.