LeetCode319- lamp switch

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Mr_wxc/article/details/102584229

Subject description:

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: 
When the initial lamp state [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.

Problem-solving ideas:

First, as a start lamp are closed, so that a lamp is lit if the last, to be bound by the odd number of times switching.

So if n k factors, and k is an odd number, then the final bright lights (e.g., 1,4,9), a 1 = 1 * 1 * 4 = 4 = 2 * 2 have only an odd number of factors

If k is an even number, the lights go off (e.g., 2,3,5) = 1 2 1 * 2 * 3 = 35 * 5 = 1 has an even number of factors

Why have an odd number of factors n n round after the operation lamp is lit, and n has an even number of factors operating after n round lamp off?

Because the factors are appearing in pairs (the equivalent of offsetting), which means that the actual play the role reversal (0-> 1), the only perfect square it

So n n light bulbs flip wheel, we only have to look to position n, a number of perfect square can be total!

Code:

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

 

Guess you like

Origin blog.csdn.net/Mr_wxc/article/details/102584229