How can I print integer in triangle form

前端 未结 4 2299
时光取名叫无心
时光取名叫无心 2021-02-13 22:20

I want to print integer in triangle form which look like this

    1
   121
  12321

I tried this but I do not get the actual result



        
4条回答
  •  遇见更好的自我
    2021-02-13 22:55

    For all the x-mas lovers:

    $max = 9; # can be 2 .. 9
    for($i = 1; $i <= $max; $i++) {
        $line = (str_pad('', $max - $i));
        for($ii = 1; $ii <= $i; $ii++) {
            $line .= $ii;
        }   
        for($ii = $i-1; $ii > 0; $ii--) {
            $line .= $ii;
        }   
        echo $line . PHP_EOL;
    }
    

    Output:

            1
           121
          12321
         1234321
        123454321
       12345654321
      1234567654321
     123456787654321
    12345678987654321
    

    Amazing what computers are able to achieve nowadays! Isn't it?

提交回复
热议问题