leetcode [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 i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Input: 3 Output: 1 Explanation: 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个灯泡都是开着的,第二轮每隔两个灯泡切换一次,第三轮每隔三个灯泡切换一次,...,第n轮每隔n个灯泡切换一次状态。
解法:
其实一开始并没有看懂题目意思,以为是第几轮就切换第几个灯泡的状态,这样最后不就只剩下一个灯泡了嘛,最后琢磨清楚了,是每隔几个灯泡切换一次。然后研究了一下,假设有5个灯泡,那么有:
初始状态: X X X X X
第一次: √ √ √ √ √
第二次: √ X √ X √
第三次: √ X X X √
第四次: √ X X √ √
第五次: √ X X √ X
最后只剩下第一和第四这两个,研究其他的也是一样的结果,发现最后求的是在n的范围里面,有几个完全平方数。尽管知道了思路,解法还是写的有点复杂。
java:
class Solution { public int bulbSwitch(int n) { int res=1; while (res*res<=n){ res++; } res--; return res; } }
简化过后的java:
class Solution { public int bulbSwitch(int n) { return (int) Math.sqrt(n); } }