search
Homephp教程php手册Look And Say 序列php实现代码

Look And Say序列,简单的说就是根据你看到的数字,写出下一个数字

比如:
第一个数字是:1。
看着第一个数字你可以说1个1,那么第二个数字就是:11。
看着第二个数字你可以说2个1,即第三个数字是:21。
看着第三个数字你可以说1个2,1个1,即第四个数字是:1211。
看着第四个数字你可以说1个1,1个2,2个1,即第五个数字是:111221。
…………
根据详细的说明可以参见:http://en.wikipedia.org/wiki/Look-and-say_sequence
下面用PHP实现这个序列,如下:
代码如下:
function look($str)
{
$len = strlen($str);
$count=0;
$result='';
$temp=$str[0];
for($i=0;$i{
if($temp!=$str[$i])
{
$result.=$count.$temp;

$temp = $str[$i];
$count=1;
}
else
{
$count++;
}
}
$result.=$count.$temp;
return $result;
}

$test_str = "1";
echo $test_str.'';
for($i=0;$i{
$test_str=look($test_str);
print $test_str."";
}

注意look函数中的for循环,当$len-1时,$result并未累加最后一位数字的统计结果,所以在循环完成后再次累加一次。

最后输出结果:

1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
11131221133112132113212221

作者:
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.