Skip to content

Instantly share code, notes, and snippets.

@imzhi
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save imzhi/1409e84b88a1f720812f to your computer and use it in GitHub Desktop.

Select an option

Save imzhi/1409e84b88a1f720812f to your computer and use it in GitHub Desktop.
从V2EX上看到的一道PHP面试题,给定一个整数n,生成一个形如[1,[2,[3,[n,"$$$$..."]]]]的数组。例如:n=4,生成[1,[2,[3,[4,"$$$$"]]]],链接:https://v2ex.com/t/182966
<?php
/**
*
* @authors imzhi (yxz_blue@126.com)
* @date 2015-08-18 19:35:20
* @version $Id$
*/
function test($n = 0) {
$arr = [];
$arr_temp = &$arr;
for ($i = 1; $i <= $n; $i++, $arr_temp = &$arr_temp[1]) {
$arr_temp[] = $i;
$arr_temp[] = $i == $n ? str_repeat('$', $n) : null;
}
return $arr;
}
$arr = test(10);
var_dump($arr);
/** 另解,原贴5楼 **/
function ba($n)
{
$a = [1, str_repeat('$', $n)];
for($i = $n; $i > 1; $i --)
{
$a[1] = [$i, $a[1]];
}
return $a;
}
$n = ba(10);
var_dump($n);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment