Php implementation code of the Look And Say Sequence

Source: Internet
Author: User

For example:
The first number is: 1.
When you look at the first number, you can say 1, then the second number is: 11.
Looking at the second number, you can say 2 1, that is, the third number is 21.
Looking at the third number, you can say 1, 2, 1, and 1, that is, the fourth number is 1211.
Looking at the fourth number, you can say 1, 1, 1, 2, 2, 1, that is, the fifth number is 111221.
............
For detailed instructions, see: http://en.wikipedia.org/wiki/Look-and-say_sequence
The following code uses PHP to implement this sequence:
Copy codeThe Code is 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> ";
}

Note the for loop in the look function, when $ len-1, $ result does not accumulate the statistical results of the last digit, so accumulate again after the loop is complete.

Final output result:

1
11
21
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.