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

问题描述 投票:0回答:4

我正在尝试编写一个 C# 方法,它接受一个整数作为输入并返回一个整数列表,这些整数是 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

我可以知道一个好方法吗?

c# bitwise-operators
4个回答
0
投票

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


0
投票

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

实现此目的的常用方法通常是检查除以 2 的模数,然后循环除以 2。


0
投票

我通过评论得到了答案

            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));
                }
            }

0
投票

我知道这是一个老问题,但我只是想提供意见。 我想提供一个 lambda 函数,它通过返回一个列表来工作,如下所示:

Func<double, List<int>> getPowersOfTwo = n => n >= 0 ? Enumerable.Range(0, 64).Where(i => ((long)n & (1L << i)) != 0).Select(i => i).ToList() : new List<int>(); 

通过这种方式,您可以检查 n > 0 并获得一个具有 2 次方的列表(如果应用),该列表的总和等于您的数字。 谢谢你

© www.soinside.com 2019 - 2024. All rights reserved.