**已关闭。**此问题需要debugging details。当前不接受答案。
编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
两年前关闭了。
Improve this question
我陷入了一个基本的算法问题,我不知道如何解决它。
基本上,我想列出一个整数的所有后代,也就是说,如果我的数字是21,我想使用它的二进制表示(10101),并列出所有至少有一个公共位的值为1的数字,以及小于21的数字,这里的结果应该是10100,10001,10000,101,100,1。
真后代的数学定义如下:
- 设h为小于2^m的非负数,其中di = 0或1。
- 设h'为另一个非负的,如
h' = d0' + d1'*2^1 + ... + dm-1'*2^(m-1)
,其中di' = 0或1。 - h'是h的后代,如果di'〈=di,且0〈=i
我尝试过很多Python和C语言的实现,也尝试过传统的纸笔技术,但都失败了。我知道这很简单,但我似乎搞不懂。我是用C语言编写代码的,所以如果你能找到一个用C语言工作的解决方案,那将是理想的,但我现在愿意接受任何东西。
3条答案
按热度按时间gopyfrb31#
下面是一个非常简单的方法:枚举
n-1
和1
之间的所有整数,并打印严格包含在n
中的整数,即:(i & n) == i
.anauzrmj2#
好吧,我终于想出了一个C代码,它看起来一点也不好看,可能优化得很糟糕,但仍然能按预期工作。可能有更简单的解决方案,但这里是我的知识目的:
bqucvtff3#
您可以使用递归解决方案,如下所示。
我有点懒,所以我没有把数字列成一个列表,而是简单地打印出来,我还打印了0和给定的数字。
我相信你可以很容易地调整代码,使它能做你想做的事情。
编译和运行结果此输出: