How can I print integer in triangle form

前端 未结 4 2304
时光取名叫无心
时光取名叫无心 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:36

    Another integer solution:

    $n = 9; 
    print str_pad ("✭",$n," ",STR_PAD_LEFT) . PHP_EOL;
    for ($i=0; $i<$n; $i++){
        print str_pad ("", $n - $i);
        for ($ii=-$i; $ii<=$i; $ii++){
          if ($i % 2 != 0 && $ii % 2 == 0)
            print "&#" . rand(10025,10059) . ";";
          else print $i - abs($ii) + 1;
        }
        print PHP_EOL;
    }
    
            ✭
            1 
           1✬1 
          12321 
         1❊3✪3✳1 
        123454321 
       1✼3✶5❃5❈3✸1
      1234567654321 
     1✾3✯5✿7❉7✫5✷3✶1 
    12345678987654321 
    

    Or if you already have the string, you could do:

    $n = 9; $s = "12345678987654321"; $i = 1;
    
    while ($i <= $n)
       echo str_pad ("", $n-$i) . substr ($s,0,$i - 1) . substr ($s,-$i++) . PHP_EOL;
    

提交回复
热议问题