Look and Say sequence PHP implementation code _php Tips

Source: Internet
Author: User
Like what:
The first number is: 1.
Look at the first number you can say a 1, then the second number is: 11.
Look at the second number you can say 2 1, that is, the third number is: 21.
Look at the third number you can say a 2, a 1, that fourth number is: 1211.
Look at the fourth number you can say a 1, a 2, 2 1, that is, the fifth number is: 111221.
............
According to the detailed instructions can see: http://en.wikipedia.org/wiki/Look-and-say_sequence
Here's how to implement this sequence in PHP, as follows:
Copy Code code as follows:

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. ' </br> ';
For ($i =0 $i <10; $i + +)
{
$test _str=look ($test _str);
Print $test _str. " </br> ";
}

Notice the For loop in the look function, and when $len-1, the $result does not add the statistic result of the last digit, so add it again after the loop completes.

Final output results:

1
11
21st
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
11131221133112132113212221

Author: ywxgod

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.