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:
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.

问题分析

参考了一篇博文。
刚开始我想直接按点灯/关灯的步骤来得到最终灯的状态,这么做非常耗时。
而其实这是一道数学题,搞懂数学原理,一个计算公式就可以得到结果。
什么样的灯最后是亮着的呢?那就是被开关奇数次的,相反,开关偶数次的最后灯是灭的。例如8 = 2 x 4,2和4是成对出现的,即一次分解就会开一次灯且关一次等,而只有9 = 3 x 3这种情况,才会出现只开灯,不关灯的情况。因此完全平方数的灯是亮的,其它都是灭的。
因此亮的灯依次为:12,22,...,⌊sqrt(n)⌋2

AC代码

class Solution(object):
    def bulbSwitch(self, n):
        """
        :type n: int
        :rtype: int
        """
        import math
        return int(math.sqrt(n))

你可能感兴趣的:(319. Bulb Switcher)