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 the i-th round, you toggle every i bulb. For the n-th round, you are only toggle the last bulb. Find How many bulbs is on after N rounds.
Example:
N
So you should return 1, because there are only one bulb are on.
Test instructions
Open n Bulbs;
The first round, each of the I bulb reversal; (2<=i<=n)
The number of light bulbs to be last lit;
Ideas:
General timeout;
Law:
N:1 2 3 4 5 6 7 8 9 10 11
Ans:1 1 1 2 2 2 2 2 3 3 3
1 class Solution {2public:3 int bulbswitch (int n) {4 return sqrt (n); 5 }6 };
View Code
--------------Update----------------
Behind the principle:
When the first wheel reverses, the light bulb State of the multiple position of I is reversed;
For the bulb I, each time to its factor will be reversed;
And the factor is usually paired, and the state is unchanged after two times reversal;
The only exception is that the two factors are the same, then only one time is reversed;
At this point, the number is the square number;
For n, the actual number of squares to be asked;
So sqrt (n).
Leetcode 319:bulb Switcher