题目:
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 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.
题意:
就是由n盏灯,初始化的时候是处于turn off(关闭)的状态,第一次的时候是将所有的灯全部点亮,第二轮的时候,是将所有的2的倍数的盏灯关闭,以此类推。。。问到第n轮之后,最后剩下多少盏灯还亮着。
题解:
此题是放在数学里的,而且也明确表明是brainteaser(脑筋急转弯)。那么必然有很巧妙的方法。所以在做的时候,我们考虑比较特殊的方法。首先通过仔细观察会发现,因为一直是关于倍数的,比如3,那么它是1->3,所以它在灭灯的时候是1,先开启灯,然后到3的时候灭灯,而之后的状态都和它无关,所以之后都关灯的,如果是4,那么它是1->2->4,其实是1 * 4 -> 2 * 2 -> 4 * 1,所以它是先开灯,然后关灯,接着再开灯,之后的状态与它也无关,所以最后它的状态就是开着的。所以发现了规律,如何判断这盏灯是否是关或者是开,采用的是如果这个盏灯的数字是平方根,那么它最后必定是开的,所以只需要判断这个n之前出现的最大的那个平方根数就行了。
public class Solution
{public int bulbSwitch(int n){return (int)Math.sqrt(n);}
}
代码非常简单,但是仔细分析就是关键。