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<$len;$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.&#39;</br>&#39;; 
for($i=0;$i<10;$i++) 
{ 
$test_str=look($test_str); 
print $test_str."</br>"; 
}

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

最后输出结果: 


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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor