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 nrounds.
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.
Subscribe
to see which companies asked this question
下面注释掉的是正常思路,
return int(math.sqrt(n))是最后AC的代码
正常思路,就是,对每次开关灯,模拟整个过程,理论上是O(n^2),不过面对999999这样的输入,显然就超时了
然后就分析,其实这就是个小学的奥数题,想来肯定有什么简单算法。然后,其实就是,开关灯次数就是这个灯序号的因子的个数,每次剩下的,都是只有奇数个因子的标号的灯,亦即,平方数。
所以,一行代码,返回平方数的个数就OK了。
class Solution(object):
def bulbSwitch(self, n):
return int(math.sqrt(n))
'''
res = [1] * (n+1)
#for i in xrange(n):
for j in xrange(2,n+1):
tmp = j
for i in xrange(1,n):
#print j,i
tmp = i*j
if tmp > n:
break
res[tmp] = 1 - res[tmp]
tmp*=j
#print res
return sum(res)-1
'''