c# - 将 1,2,3,4,5,6,8,10,11 显示为 1-6,8,10-11

标签 c# java algorithm logic

I have this sequence 1,2,3,4,5,6,8,10,11

Expected output is 1-6,8,10-11

这个问题是关于以易于阅读的形式格式化序列

我尝试使用 C# 并使用了很多 if & else。

面试官说,有一些简单的算法可以做到这一点。

我不知道如何实现这个非常简单。

Also for 1,2,3 i shown 1-3. They said its wrong!.

这个逻辑有没有涉及到设计模式(解释器)?

最佳答案

这是一种实现方式:

        int[] numbers = { 1, 2, 3, 4, 5, 6, 8, 10, 11 };

        int start, end;
        for (int i = 0; i < numbers.Length; i++)
        {
            start = numbers[i];

            while (i < numbers.Length - 1 && numbers[i] + 1 == numbers[i + 1])
                i++;

            end = numbers[i];

            if(start == end)
                Console.WriteLine(start);
            else
                Console.WriteLine(start + " - " + end);
        }

这将显示随范围递增的后续数字。不是线性增加的数字不作为范围的一部分写入。

这是第一种方法的另一个版本,它使用相同的 for 循环来迭代范围:

        int temp = numbers[0], start, end;
        for (int i = 0; i < numbers.Length; i++)
        {
            start = temp;

            if (i < numbers.Length - 1 )
                // if subsequent numbers are incremental loop further
                if (numbers[i] + 1 == numbers[i + 1])
                    continue;
                // if they are not, number at index i + 1 is a new 'start' for the next iteration
                else
                    temp = numbers[i + 1];

            end = numbers[i];

            if (start == end)
                Console.WriteLine(start);
            else
                Console.WriteLine(start + " - " + end);
        }

关于c# - 将 1,2,3,4,5,6,8,10,11 显示为 1-6,8,10-11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14952818/

相关文章:

java - 读取/写入 .properties 文件的实用程序类的测试环境

java - Java中特定的字符串输入

php - PHP如何判断变量是否为小数且小于0.01?

algorithm - 这使用什么分区算法? (用于快速排序)

c# - 使用 Entity Framework 和 MySQL 实现 MassTransit saga 持久性

c# - 在 C++ 中实现接口(interface)

c# - 如何测试所有 ASP.NET Core Controllers 的依赖注入(inject)是否有效?

c# - StackTrace/StackFrame 不返回生产环境中的预期信息

Java 控制台循环

algorithm - Haskell递归 - 找到列表中数字之间的最大差异