算法以m 1s获取每一个二进制长度n的二进制数

发布于 2025-01-23 10:35:24 字数 386 浏览 0 评论 0原文

我正在寻找一种快速的方法来生成每个长度n的二进制数,其中包含m 1s。

因此,例如,如果n = 3,m = 2,则只是:110,011,101

幼稚的方法是通过12^n -1之间的数字进行迭代,检查每个值的二进制表示是否包含m 1s。另外,使用一些算法来获取m 1s和n -m 0s的每种组合。

但是,我想知道是否有更快的方法可以使用位运算符进行此操作,或者可能在其二进制表示中具有m 1s的数字属性可以被利用。

I'm looking for a quick way to generate every binary number of length n which contains m 1s.

So for example, if n=3, m=2, this would just be: 110, 011, 101.

The naive approach would be to iterate through numbers between 1 and 2^n - 1, checking if each value's binary representation contains m 1s. Alternatively, using some algorithm to get each combination of m 1s and n - m 0s.

However, I'm wondering if there might be some quicker way to do this with bitwise operators, or perhaps a property of numbers with m 1s in their binary representation that could be exploited.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青芜 2025-01-30 10:35:24

- 首先您需要将“ 1”放在位置n
- 然后,您需要将M-1 1'1'放在0到N-1的位置。
- 您需要梳子(N-1,M-1)才能执行此操作,例如使用重复出现的算法(要将M-1'1'放在N-1位置,您将1放在i = n-1的位置上I-1位置的-2和M-2'1'。

-First you need to put a '1' in position n
-Then you need to put m-1 '1' in the positions 0 to n-1.
-You need Comb(n-1,m-1) to do this, for example using a recurring algorithm (to put m-1 '1' in n-1 positions you put a 1 in positions i= n-1 to m-2 and m-2 '1' in i-1 positions.

柳若烟 2025-01-30 10:35:24
  1. 如果您只想计算所有可能的二进制数字,则答案将为NCM IE C(n,m)=(n! /(m! *(n -m)!)。请参阅此处。(有关数学概念的解释: Combination概念: Combination。)。)。)。

  2. )如果您需要找到所有数字,那么此问题与:“找到M设置位的所有可能的二进制字符串” “>您可以参考此情况。

  1. If you want only to count all possible binary numbers, then the answer will be nCm i.e C(n,m) = (n! / (m! * (n−m)!). See here. (for an explanation of the mathematical concept: combination.)

  2. If you need to find all numbers, then this problem is the same as: "Find all the possible Binary strings of size n having m set bits". You can refer to this for this case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文