在将整数转换为按位其总和等于输出整数总和后计算 2 的各个幂

Calculating individual powers of 2 after converting an integer to a bitwise whose sum is equal to sum of output integers

我正在尝试编写一个 c# 方法,它接受一个整数作为输入,returns 一个整数列表,它是 2 的幂,其总和等于输入整数

例如

Input Integer :15
Output of this should be 1(2^0), 2 (2^1), 4 (2^2), 8 (2^3)
Sum of above integers is 15 = Input Integer


Input Integer :13
Output of this should be 1(2^0), 4 (2^2), 8 (2^3)
Sum of above integers is 13 = Input Integer


Input Integer :8
Output of this should be: 8 (2^3)
Sum of above integers is 15 = Input Integer

请问有什么好的方法吗?

数字的二进制表示实际上是 2 的幂和该数字之和的位图。只需从 LSB 到 MSB 迭代这些位,为设置为 1 的每个位发出适当的字符串。

通常,您需要数字的二进制表示。输出是表示具有位置的位置列表(向后计数)。

实现这个的通常方法通常是检查除以 2 的模数,然后除以 2 - 在一个循环中。

我通过评论得到了答案

            var bits = new BitArray(BitConverter.GetBytes(12));
            List<Double> restrictedList = new List<Double>();
            for(int i=0;i<bits.Count;i++)
            {
                if (bits[i]==true)
                {
                    restrictedList.Add(Math.Pow(2, i));
                }
            }