思維體操:用c#簡單實現按一定規則輸出有序數列

來源:互聯網
上載者:User
要求:輸入一個整數num,列印出如下規則的一組數字:1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
... ...

比如輸入數字7,應該有如下輸出:

1
2 3
4 5 6

下面是用c#的簡單實現:

代碼

        public static void Print(int num)
        {
            int counter = 1;
            for (int i = 0; i < num; i++)
            {
                StringBuilder sb = new StringBuilder(100);
                for (int j = 0; j < i + 1; j++)
                {
                    int output = j + counter;

                    sb.AppendFormat("{0}  ", output);
                    if (j == i)
                    {
                        counter = output + 1;//下一行的第一個數字是前一行的最後一個加1
                    }
                    if (output == num)
                    {
                        counter = num;//是最後一個數字 跳出迴圈
                        break;
                    }
                }
                Console.WriteLine(sb.ToString());
                if (counter == num)
                {
                    return;
                }
            }

        }

        static void Main(string[] args)
        {
            Print(1);
            Console.WriteLine("--------------");

            Print(7);
            Console.WriteLine("--------------");

            Print(10);
            Console.WriteLine("--------------");

            Print(15);
            Console.WriteLine("--------------");

            Print(30);
        }

分析上面的代碼,我個人認為這是最簡單明了符合常規認知的一種實現:要輸出有序序列的數字,找出數字排列的規律,找到這個規律,最後就是水到渠成的編程實現罷了。
最後賣個關子,其實它還有一種代碼更加簡潔的實現,是從某高手那裡偷師的,大家不妨動手練習一下吧,這個還是很能考驗一個人的邏輯思維的。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.