319. Bulb Switcher

問(wèn)題描述

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.

問(wèn)題分析

參考了一篇博文
剛開(kāi)始我想直接按點(diǎn)燈/關(guān)燈的步驟來(lái)得到最終燈的狀態(tài),這么做非常耗時(shí)。
而其實(shí)這是一道數(shù)學(xué)題,搞懂?dāng)?shù)學(xué)原理,一個(gè)計(jì)算公式就可以得到結(jié)果。
什么樣的燈最后是亮著的呢?那就是被開(kāi)關(guān)奇數(shù)次的,相反,開(kāi)關(guān)偶數(shù)次的最后燈是滅的。例如8 = 2 x 4,2和4是成對(duì)出現(xiàn)的,即一次分解就會(huì)開(kāi)一次燈且關(guān)一次等,而只有9 = 3 x 3這種情況,才會(huì)出現(xiàn)只開(kāi)燈,不關(guān)燈的情況。因此完全平方數(shù)的燈是亮的,其它都是滅的。
因此亮的燈依次為: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))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 10,992評(píng)論 0 23
  • 不知道你沒(méi)有曾經(jīng)有那么一刻或一段時(shí)間感到過(guò)孤獨(dú),孤獨(dú)這個(gè)詞在現(xiàn)在這個(gè)時(shí)代已經(jīng)被大多數(shù)人模糊,孤獨(dú)的深刻或許他們從來(lái)...
    狗尾巴草焚燒的小鎮(zhèn)閱讀 206評(píng)論 0 1
  • 韶華易逝,流年難追。在這有限的一生,你那林林種種的往事,你那紛紛擾擾的思緒,你那凄凄涼涼的心事,以及你那不為他人所...
    溜大姑娘閱讀 276評(píng)論 0 4
  • /無(wú)意間看一篇關(guān)于20歲的中國(guó)女留學(xué)生在加州一所大學(xué)宿舍內(nèi)自殺的報(bào)道。第一次聽(tīng)說(shuō)‘微笑抑郁癥’這個(gè)概念。想起當(dāng)年自...
    Ann_四月天兒閱讀 393評(píng)論 2 3
  • 歸途此生漸逐開(kāi),雨落雙鬢憶緒衰。 伊人剎離陌路寒,青蔥情愫已惘然。 待到甲子年更幻,與爾隨行西湖畔。
    九尾老貓閱讀 216評(píng)論 0 0

友情鏈接更多精彩內(nèi)容