This is a very ingenious topic, the site is called brain teaser, meaning that the code will be very brief description (is to tease you to play:)), the topic is as follows:
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 n-th round, you are only toggle the last bulb. Find How many bulbs is on after N rounds.
Example:
given n = 3.
at first, the three bulbs is [off, off, off]. After first round, the three bulbs is [on, on,]. After second round, the three bulbs is [on, off, on]. After third round, the three bulbs is [on, off, off].
so you should return 1, because there are only one bulb are on.
first: 1x1 only in this case, so all the bulbs are off--and on
second: 2x1 1*2 that is to say there will be two switch, one is 1 for the interval switch, and the other is 2 is the interval switch,off->on-->off
third: 1x3 3x1,off-->on-->off
,,,,
and so on, we find that a*b always has a b*a counterpart, that is, an even number of switch, so that the off or off,on or on, that is, to remain unchanged, in addition to a situation, is 3x3 this, if the sqrt (interval) is an integer, Indicates that there is an odd number of switch, the state changes will occur, then we can now consider this problem is very simple, because at the beginning all the bulbs are extinguished, so we just need to look for 1. Less than n,2. And sqrt is the number of integers. The answer is obviously sqrt (n)
Code:
class Solution {public: int bulbswitch (int n) { return (int) sqrt (n); }};
Leetcode 319. Bulb switcher