[英]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.