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 );}}}