有这么一个对应:
Key:1,2,3,4,5,6,7,8
Value:1,2,4,8,16,32,64,128
现给定一个正整数N,它是由Value中的某些元素相加得到的,
求这些元素的Key.
例如,N=169,因为1+8+32+128=169,所以组成169的Key就是: 1,4,6,8.
求高手解答啊!算法数列2的n次方
Key:1,2,3,4,5,6,7,8
Value:1,2,4,8,16,32,64,128
现给定一个正整数N,它是由Value中的某些元素相加得到的,
求这些元素的Key.
例如,N=169,因为1+8+32+128=169,所以组成169的Key就是: 1,4,6,8.
求高手解答啊!算法数列2的n次方
当输入一个和值时,直接拿出对应元素编号不就ok了。
Dictionary<int, int> dic = new Dictionary<int, int>() {
{1,1},
{2,2},
{3,4},
{4,8},
{5,16},
{6,32},
{7,64},
{8,128}
};
int result = 169;
List<int> keyList = new List<int>();
foreach(var keyItem in dic)
{
if ((result & keyItem.Value) != 0)
{
keyList.Add(keyItem.Key);
}
}
/*keyList
* [0] 1 int
[1] 4 int
[2] 6 int
[3] 8 int
*/
{
BitFlag testFlag = (BitFlag)169;
Console.WriteLine(testFlag.ToString());
} [Flags]
public enum BitFlag
{
Bit01 = 0x0001,
Bit02 = 0x0002,
Bit03 = 0x0004,
Bit04 = 0x0008,
Bit05 = 0x0010,
Bit06 = 0x0020,
Bit07 = 0x0040,
Bit08 = 0x0080
}
也
行
??
为啥不行,169 不就对应 1,4,6,8,不就是
Bit01, Bit04, Bit06, Bit08
不过还是领教了!多谢
var d = 1;
for (var i = 1; i < 30; i++)
{
if ((d & n) != 0)
Console.Write("{0} ", i);
d = d << 1;
}这不算什么算法。算法的概念不适合定得太低。
Bit01Bit04Bit06Bit08