leetcode 319. Bulb Switcher

来源:互联网 发布:指南针炒股软件好吗 编辑:程序博客网 时间:2024/05/29 15:50

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.

开关灯步骤是这样的:

1. You first turn on all the bulbs.
2. Then, you turn off every second bulb.(2, 4, 6, ...)
3. On the third round, you toggle every third bulb.(3, 6, 9, ...)
4. For the ith round, you toggle every i bulb.(i, 2i, 3i, ...)
5. For the nth round, you only toggle the last bulb.(n)

这道题,不要妄图想用程序推演过程,然后数结果中有多少亮着的灯泡,你会TLE的。这道题。。。就是个数学问题!

public int bulbSwitch(int n) {return (int)Math.sqrt(n);}
为啥是根号n呢?
如果一个灯泡被开关了奇数次,那么它最后将是on的状态。
假设灯泡1到灯泡n,其中当且仅当 i 能被 d 整除时,灯泡 i 才会在第 d 个回合被开关。所以当灯泡 i 有 奇数个 除数时,它的结束状态是on。
除数都是成对出现的, i=12 有除数 1 和 12,2 和 6, 3 和 4。除非 i 是平方数,比如 36 有除数 1 和 36,2 和 18,3 和 12,4 和 9,以及 6。所以灯泡 i 当且仅当 i 是平方数时,结束状态才是on.
因此,问题简化为:得到1~n中 平方数的个数。
算出R = int(sqrt(n)). R是 [1,n] 范围内最大的平方数。并且1是最小的平方数,因此平方数是从1~R,共计有R个平方数。


原创粉丝点击