c# - 构造一个整数数组来实现特定的序列

标签 c#

construct the shortest possible sequence of integers ending with A, using the following rules:

the first element of the sequence is 1, each of the successive elements is the sum of any two preceding elements (adding a single element to itself is also permissible), each element is larger than all the preceding elements; that is, the sequence is increasing.

For example, for A = 42, a possible solutions is [1, 2, 3, 6, 12, 24, 30, 42]. Another possible solution is [1, 2, 4, 5, 8, 16, 21, 42].

我编写了以下内容,但在输入 456 时失败,通过返回 [1,2,4,8,16,32,64,128,200,256,456] ,序列中没有可以加在一起得到 200 的数字。

如何修复以下代码?我做错了什么?

  public static int[] hit(int n)
    {
        List<int> nums = new List<int>();

        int x = 1;

        while (x < n)
        {
            nums.Add(x);
            x = x * 2;

            if (x > n)
            {

                    nums.Add(n - (x / 2));

                nums.Add(n);
            }
        }

        nums.Sort();
        int[] arr =  nums.ToArray();
        return arr;
    }

最佳答案

我知道这背后会有一个数学证明,但我的猜测是将数字除以 2,如果它相等,则重复该过程。如果有余数,则为 1。因此您将得到整数商和商加一。由于保证其中有一个数字存在,因此 2 个数字中较大的一个已被处理。因此,只需对较小的重复该过程即可。这个问题肯定意味着一个相对简单的递归解决方案,所以我将把它留给发布者来实现。

关于c# - 构造一个整数数组来实现特定的序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10364534/

相关文章:

c# - .NET Web API(非核心)- 在 Entity Framework Controller 中创建修补操作

c# - MemoryStream 返回时禁用读取

c# - 为什么 AppDomain.CurrentDomain.GetAssemblies() 在某些情况下不返回 Global.asax 中的依赖程序集?

c# - 如何在 WP7 应用程序中循环显示多个图像?

c# - 调用 native 代码的多线程托管应用程序

c# - 调用方法时如何在 C# 代码中激活 UAC?

c# - 绑定(bind)数据网格列可见性 MVVM

c# - 从多个表中选择 MAX

c# - 使用 XPath 绑定(bind)表达式时,是否可以取回 InnerXml 而不是 InnerText?

c# - 使用枚举访问 xaml 中的数组