2017-03-13 5 views
1

私が知りたいのは、Nビットが32ビットのうち1ビットに設定されている場合に設定できる数値の数です。N個のビットが設定されている場合、Int32の数はどのくらい表示できますか?

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; 
    } 
+0

[組み合わせ](https://en.wikipedia.org/wiki/Combinati)の数学概念のようですon)) –

+0

事前計算コードにはバグがあります。現在、 'Int32 .MaxValue'。 –

+0

okこれはi MajorInc

答えて

4

:サイズはnInt32の場合32)であり、我々は設定正確kビットを持っている場合、我々はC(k, n)がの略

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

番号を表すことができます。

編集

:コメントで述べた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; 
} 
+0

ありがとうthats私はその二項係数...と思ったどこでもC#コード? – MajorInc

+1

32歳なので! 'int'や' long'でもあふれてしまった場合、オーバーフローを避けるために何をすべきかを述べるべきです。 – dasblinkenlight

+0

@MajorInc参照[この質問](http://stackoverflow.com/questions/12983731/algorithm-for-calculating-binomial-coefficient) – Pikoh

関連する問題