Lamp switch

When n initial lamp is switched off. Round 1, you open all the bulbs. The first two, shut down once every two bulbs you. Round 3, once every three-lamp switching switch (if it is turned off, and if turned on off). The i-th round, switching every time the i-th lamp switch. For the n-th wheel, you only have to switch the last lamp switch. After n rounds to find out how many lit bulb.

Example:

Input: 3

Output: 1

Explanation:

Initially, the lamp status [close, close, close].

After the first round, lamp status [Open, Open, Open].

After the second round, lamp status [On, Off, On].

After the third round, lamp status [on, off, off].

You should return 1, because there is only one light bulb is still on.

Source: stay button (LeetCode) link: https: //leetcode-cn.com/problems/bulb-switcher network all the copyright collar button.

 

Analysis: for example: n = 10, the start of all the lamps are closed.

The first position, 1 * 1 = 1, the state is changed to 1;

A second position, 2 * 1 = 2, was changed twice (2);

Third position, 1 * 3 = 3, it was changed twice (1,3);

The fourth position ( Note that there is something new ), 1 * 4 * 2 = 4,2 = 4, was changed three times (2,4);

Fifth position, 5 * 1 = 5, it was changed twice (1,5);

.........

Eighth positions, 1 = 8,2 * 8 * 8 = 4, was changed four times (1,2,4,8);

Ninth positions, 1 * 9,3 * 3 = 9 = 9, was changed three times (3, 9);

Tenth positions, 1 * 5 * 10 = 10, 2 = 10, was changed four times (1,2,5,10);

 

Law: who can open square of the position (including the position 1) the base times have changed, others are even times (because of the emergence of these factors in pairs). And changing the position of the base position of the STATUS times remains lit state, even-numbered was off.

  So the problem and minimize the number n and the number n of all of the following can be openable side;

  

    public int bulbSwitch(int n) {
        return (int)Math.sqrt(n);
    }

 

Guess you like

Origin www.cnblogs.com/blog-of-zxf/p/11329753.html