gpt4 book ai didi

algorithm - 金字塔数算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:33 25 4
gpt4 key购买 nike

我想生成这样的静态金字塔:

1 2 4 8 16 32 64 128 64 32 16 8 4 2 1 
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 4 2 1
1 2 4 2 1
1 2 1
1

使用 PHP,我已经创建了这段代码:

<center>
<?php
$x1 = 1; $x2 = 128;
$str_tmp = "";
$cek = 0;
$start = 0;
for($i=0;$i<=7;$i++){
for($j=$i;$j<=13;$j++){
for($z=$i;$z<$i;$z++){
$str_tmp.= ("&nbsp") ;
}
if($x2==1){
$str_tmp.= $x2;
break;
}
if($cek==0){
$str_tmp.= $x1 . " ";
$x1 = $x1 * 2;
if($x1==$x2){
$cek = 1;
$x2 = $x2/2;
}
}if($cek==1){
$str_tmp.= $x1 . " ";
$x1 = $x1 /2;
}if($cek==1&&$x1<1){
break;
}
}
echo $str_tmp."</br>";
$str_tmp = "";
$x1 = 1;
$cek = 0;
}
?>
</center>

我觉得它看起来太复杂了。你们有更好的解决方案吗?我不介意你们用另一种语言编写代码。

谢谢

最佳答案

是这样的吗?

echo "<div style=\"text-align: center;\">";

for ($l=7; $l>=0; $l--){

$str = "";

for ($p=-$l; $p<=$l; $p++)
$str .= (1 << ($l - abs($p))) . " ";

echo substr($str,0,-1) . ($l ? "<br>" : "");
}

echo "</div>";

关于algorithm - 金字塔数算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29536203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com