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:
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.
看了discuss之后,心好累。
https://leetcode.com/problems/bulb-switcher/
我的代码:
class Solution(object):
def bulbSwitch(self, n):
if not n:return 0
if n==1:return 1
ans=0
i=1
while i<=n:
ans+=self.count(i)
i+=1
return ans
def count(self,n):
i=1
ans=1
l=n//2
while i<=l and i<n:
if not n%i:ans^=1
i+=1
return ans
会超时,嗯~~
百思不得其解~~
结果只需要开根号就可以了~~
为什么呢?
举例说明:
比如说第12个灯,它什么时候会开会关呢?
第1\12,2\6,3\4 次操作对吧结果很惨对吧
但是如果是完全平方数呢?
比如36~~
它只有一个6,这个只进行了奇数次操作。
所以这个题目就是 找完全平方数的个数
开个根号就好了