Interview question 1
I recently saw an interview question on the Internet and made it as I started my blog.
I recently learned PHP, so I used PHP to solve it. However, the world language is one, and other languages can also be referred. The question is simple as follows:
There are 100 lamps in the hall, each of which is numbered from 1 to 100. Each lamp is controlled by a switch. (Click the switch, the light is on, and then the light is off. The switch number is the same as that of the controlled lamp .) At the beginning, the light is completely off. Click the switch according to the following rules.
For the first time, light up all the lights.
For the second time, click the switch in multiples of all 2.
For the third time, click the switch of all multiples of 3.
And so on. Next, click the switch that multiples of all N.
After 100th press times, there are still several lights on in the hall.
The method is as follows:
1 <? Php 2 3 // totle: Total number of lamps, times: Number of active switches 4 function switchLight ($ totle, $ times) {5 // define the status attribute 6 $ on = 1; 7 $ off =-1; 8 // define an active/standby switch action 9 $ oc =-1; 10 // create an array, dynamically store the number of lamps, and initialize status 11 $ lights = array (); 12 for ($ I = 1; $ I <= $ totle; $ I ++) {13 $ lights [$ I] = $ off; 14} 15 // determine the case where no force switch is triggered 16 if ($ times = 0) {17 return 0; 18} 19 // cyclically judge, and press switch 20 for ($ j = 1; $ j <= $ times; $ j ++) {21 for ($ k = 1; $ k <= $ totle; $ k ++) {22 if (! ($ K % $ j) 23 $ lights [$ k] * = $ oc; 24} 25} 26 // traverse all the lights on, and save the new array 27 $ newLights = array (); 28 for ($ r = 1; $ r <= $ totle; $ r ++) {29 if ($ lights [$ r] ==$ on) {30 $ newLights [] = $ r; 31} 32} 33 return $ newLights; 34 35} 36 37 $ newLights = switchLight (100,100); 38 echo "The result is ". count ($ newLights ). "Lighting, details:"; 39 foreach ($ newLights as $ light) {40 echo $ light; 41 echo "\ n"; 42} 43?>
There is a better method and will be updated later.