algorithm - 在 C 中有效地生成所有整数 n,其中 n&m==n(m 是给定的整数)

标签 algorithm bit-manipulation bitwise-operators

& 在 C 中是位与。

示例:

m= 21(10101)

结果:

0 16 4 1 20 5 17 21

我的代码:

for(int i=0;i<=m;i++) 
    if ((i&m)==i) printf("%d ",i);

当 m 很大时,这会很慢。

如何快速找到结果(答案很少时,比如m=2^30)?

最佳答案

i = 0
repeat
  print(i)
  i = (i + (NOT m) + 1) AND m
until i == 0

更新:
更简单的代码:

i = 0
repeat
  print(i)
  i = (i - 1) AND m
until i == 0

关于algorithm - 在 C 中有效地生成所有整数 n,其中 n&m==n(m 是给定的整数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16507690/

相关文章:

algorithm - 寻找强连通分量?

python - Python/numpy 中的快速/内置位操作?

c++ - C/C++ 检查是否设置了一位,即 int 变量

c# - 减去两个 System.Runtime.InteropServices.ComTypes.FILETIME 对象的最安全方法是什么

algorithm - 在集合中寻找模式

algorithm - 给定一组非负整数元组,一些预处理是否可以快速判断集合中的某些元组是否支配给定的查询元组?

java - 剪刀石头布的可扩展解决方案

c++ - 性能方面,按位运算符与普通模数相比有多快?

SQL Server 按位处理,如 C# 枚举标志

Go << 和 >> 运算符