日期:2014-05-20  浏览次数:20576 次

求算法(2^0,2^1,2^2,2^3,2^4...)随便给出一个值21就能知道其组合?
一序列:2^0,2^1,2^2,2^3,2^4...
随便给出一个值21,即知道21=2^0+2^2+2^4
再如给出一个值9,即知道9=2^0+2^3
...
该算法如何实现?谢谢了

------解决方案--------------------
string str = Convert.ToString(21, 2);
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i,1)== "1 ")
{
MessageBox.Show( "选中: " + i );
}
}
------解决方案--------------------
OK
调试通过了
int a = 21;
List <int> Index = new List <int> ();
int i=0;
while (a != 0)
{
int b = a > > 1;
if(a-b*2 != 0)
Index.Add(i);
i++;
a > > = 1;
}

string result= " ";
for(int j=0;j < Index.Count;j++)
{
result += Index[j].ToString() + ", ";
}
MessageBox.Show(result);