Php classic interview questions: Monkey King's question

Source: Internet
Author: User
It is said that this is a Sina interview question, which has been reprinted by many companies and organizations. it is a classic question. The question is called the Monkey question in a friendly way. the general meaning of the question is as follows:

It is said that this is a Sina interview question, which has been reprinted by many companies and organizations. it is a classic question. the question of 'Monkey Kings' is a kind of question. the general meaning of the question is as follows:

A group of monkeys are arranged in a circle and numbered by 1, 2,... and n.

Then start counting from 1st, count to m, kick it out of the circle, start counting from behind it, count to m, and kick it out ...,

The monkey is called the King until there is only one monkey.

Requirement: program to simulate this process, input m, n, and output the number of the last king.

Here is a solution that you think is easier to understand:

 
 
 
Function getKingMonkey ($ n, $ m) {$ monkey = range (1, $ n); // Construct a monkey array $ I = 0; // traverse the monkey array while (list ($ k, $ value) = each ($ monkey) {if (count ($ monkey) = 1) {echo $ value. "Is monkey King"; exit () ;}if (++ $ I ==$ m) {echo $ monkey [$ k]. 'kick out '.'
'; Unset ($ monkey [$ k]); // clear the variable $ I = 0; // pointer ing} // if the number has reached the end, continue the next round of loop if (! Current ($ monkey) {reset ($ monkey );}}}

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.