c#只用一个for输出三角形

近日到某公司面试,其中有道面试题是这样的:

要求只使用一个for循环输出下面图形:

----

如果可以使用2个for(即嵌套循环的话),那这题就很简单了。

但只能用一个for,这可把我想得,想到面试都结束了没想出来。

TMD,肯定是脑子短路了!!!

  郁闷的是,等到第2天重新一想,居然很快就想出来了,使用String对象,可以达成输出重复字符的效果!!!

 代码贴在下面:

 

代码
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    
class Program
    {
        
static void Main(string[] args)
        {
            Render(
19);

            Console.Read();
        }

        
static void Render(int rowNum)
        {
            
if (rowNum <= 0 || !System.Text.RegularExpressions.Regex.IsMatch(rowNum.ToString(),@"^\d+$"))
                
return;
            
int tmpRow = 0;
            
for (int i = 1; i <= rowNum; i++)
            {
                
//对称输出
                tmpRow = i <= rowNum / 2 ? i : rowNum - i + 1;               
                Console.WriteLine(
"{0}"new string('*'2 * tmpRow - 1));
            }
        }
    }
}

 --下面是php版本

 

 1 <?php
 2 //phpinfo();
 3   function Dis($num)
 4   {
 5       if($num<=0)
 6        return;
 7       $tmpRow=0;
 8       for($i=1;$i<=$num;$i++)
 9       {
10           $tmpRow=$i<=$num/2 ? $i:$num-$i+1;
11           echo str_repeat('*',2*$tmpRow-1).'<br />';
12       }
13   }
14   
15   Dis(19);
16 ?>

 

 

 

很简单的东西,把我给卡住了。

类似的东西还有:如何在for里面实现不间断的循环?《在for里面改变for的条件就是了》

----------------------------------------------------------------------

间隙性的知足,以儆效尤!!!

posted @ 2010-03-30 11:31  mcjeremy  阅读(3504)  评论(6编辑  收藏  举报
------------------------------------ 心静似高山流水不动,心清若巫峰雾气不沾 ------------------------------------