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:
|
|
数学
最优的算法,看了很多解释,觉着这个解释最好,摘录过来:
|
|
为什么只有完全平方数的因子个数为奇数呢?
因为除了完全平方数,其余数字的因子都是成对出现的,而完全平方数的平方根只会统计一次。
前10盏灯泡的开闭过程如下所示:
|
|
代码如下:123public int bulbSwitch(int n) { return (int) Math.sqrt(n);}
Ref:
http://bookshadow.com/weblog/2015/12/19/leetcode-bulb-switcher/