319. Bulb Switcher

There are n bulbs that are initially off. You first turn on all 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 ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

Example:

Given n = 3. 

At first, the three bulbs are [off, off, off].
After first round, the three bulbs are [on, on, on].
After second round, the three bulbs are [on, off, on].
After third round, the three bulbs are [on, off, off]. 

So you should return 1, because there is only one bulb is on.

一刷
题解:初始,每个灯泡off
第一轮,每1个灯泡切换状态
第二轮,每2个灯泡切换状态
第n轮,每n个灯泡切换状态, 问最后有几盏灯泡是亮的

当一个灯泡被执行偶数次switch操作时它是关着的,当被执行奇数次switch操作时它是开着的,那么这题就是要找出哪些编号的灯泡会被执行奇数次操作。
j=12时,编号为12的灯,在第1次,第12次;第2次,第6次;第3次,第4次一定会被执行Switch操作,这样的话,编号为12的等肯定为灭。
但是当完全平方数36就不一样了,因为他有一个特殊的因数6,这样当i=6时,只能被执行一次Switch操作,这样推出,完全平方数一定是亮着的,所以本题的关键在于**找完全平方数的个数。 **

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

你可能感兴趣的:(319. Bulb Switcher)