【leetcode题解】【M】Bulb Switcher

175 篇文章 0 订阅
157 篇文章 0 订阅

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
        '''



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值