Topic:
There is n bulbs that is initially off. You first turn the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For then-th round, you are only toggle the last bulb. Find How many bulbs is on afterN rounds.
Example:
N [Off, off, off] [on, on, on] [on, Off, on] [on, off, off]. So you should return 1, because there are only one bulb are on.
Answer:
We know that whenever a light bulb changes state, that is, toggle, it is because it appears on the integer multiples of a number.
For the 1th bulb: 1*1, it will change 1 times, i.e. off-"on
For the 2nd bulb: 1*2,2*1, it will change 2 times, i.e. off-"on-" off
For the 3rd bulb: 1*3,3*1, it will change 2 times, i.e. off-"on-" off
For the 4th bulb: 1*4,2*2,4*1, it will change 3 times, i.e. off-"on-" off-"on
......
Will find that whenever I find an integer multiple of a number, I always find an integer multiple of symmetry , for example 1*2, there will certainly be a 2*1. The only exception appears on the square number, for example 4 = 2*2, with only one integer multiple.
Each time as an even number of integers, the final bulb will revert to off, and the final bulb will be switched on only as an odd number of times.
That is, the number of light bulbs that are finally lit is determined by the maximum number of squares less than. The code is simple:
Class Solution {public: int bulbswitch (int n) { return (int) sqrt (n); }};
"Leetcode from zero single brush" Bulb switcher