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))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,890评论 0 23
  • 不知道你没有曾经有那么一刻或一段时间感到过孤独,孤独这个词在现在这个时代已经被大多数人模糊,孤独的深刻或许他们从来...
    狗尾巴草焚烧的小镇阅读 188评论 0 1
  • 韶华易逝,流年难追。在这有限的一生,你那林林种种的往事,你那纷纷扰扰的思绪,你那凄凄凉凉的心事,以及你那不为他人所...
    溜大姑娘阅读 261评论 0 4
  • /无意间看一篇关于20岁的中国女留学生在加州一所大学宿舍内自杀的报道。第一次听说‘微笑抑郁症’这个概念。想起当年自...
    Ann_四月天儿阅读 341评论 2 3
  • 归途此生渐逐开,雨落双鬓忆绪衰。 伊人刹离陌路寒,青葱情愫已惘然。 待到甲子年更幻,与尔随行西湖畔。
    九尾老猫阅读 200评论 0 0