1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
... ...
2 3
4 5 6
7 8 9 10
11 12 13 14 15
... ...
比如输入数字7,应该有如下输出:
1
2 3
4 5 6
7
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 );
}
{
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 );
}
分析上面的代码,我个人认为这是最简单明了符合常规认知的一种实现:要输出有序序列的数字,找出数字排列的规律,找到这个规律,最后就是水到渠成的编程实现罢了。
最后卖个关子,其实它还有一种代码更加简洁的实现,是从某高手那里偷师的,大家不妨动手练习一下吧,这个还是很能考验一个人的逻辑思维的。