要求:輸入一個整數num,列印出如下規則的一組數字:1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
... ...
比如輸入數字7,應該有如下輸出:
1
2 3
4 5 6
7
下面是用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);
}
分析上面的代碼,我個人認為這是最簡單明了符合常規認知的一種實現:要輸出有序序列的數字,找出數字排列的規律,找到這個規律,最後就是水到渠成的編程實現罷了。
最後賣個關子,其實它還有一種代碼更加簡潔的實現,是從某高手那裡偷師的,大家不妨動手練習一下吧,這個還是很能考驗一個人的邏輯思維的。