簡體   English   中英

設置N個位數時,可以表示多少個Int32數字?

[英]How many Int32 numbers can be represented when N number of bits is set?

我想知道的是,如果將32位中的N位設置為1,則可以設置多少個數字。

Example lets try with 4 bits
//HowMany(1) = 4
//1000
//0100
//0010
//0001
//
//HowMany(2) = 6
//1001
//1010
//1100
//0110
//0101
//0011

public int HowMany(int bits)
{
    ....
}

我正在嘗試為此計算一個預先計算的字典,但它需要花費很多時間:

    var dict = new Dictionary<int, int>();
    for (int i = 0; i <= Int32.MaxValue; i++)
    {
        var str = Convert.ToString(i, 2);
        var count = str.Count(x => x == '1');
        if (!dict .ContainsKey(count))
            dict .Add(count, 0);
        dict [count] += 1;
    }

輕松地:如果size為n (如果是Int32則為32 )並且我們恰好設置了k位,我們可以表示

  C(k, n) = n! / (k! * (n - k)!)

數字,其中C(k, n)代表二項式系數

編輯 :作為dasblinkenlight在評論中提到的32! 是一個甚至超過 long.MaxValue巨大數字 ,因此,可能更實用的公式是

  C(k, n) = n * (n - 1) * ... * (n - k + 1) / k!

可能的C#實現:

private static long HowMany(int k, int n = 32) {
  long result = 1;

  for (int i = 0; i < k; ++i)
    result *= (n - i);

  for (int i = 1; i <= k; ++i)
    result /= i;

  return result;
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM