LeetCode-319~Bulb Switcher燈泡開(kāi)關(guā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.
共有n個(gè)燈泡,初始狀態(tài)是關(guān)閉的。第一輪,打開(kāi)所有燈泡,第二輪關(guān)掉所有2的倍數(shù)的燈泡,第三輪轉(zhuǎn)換所有3的倍數(shù)的燈泡開(kāi)關(guān)狀態(tài),以此類推,知道第n輪,轉(zhuǎn)換所有n的倍數(shù)的燈泡開(kāi)關(guān),找出有幾盞燈泡是開(kāi)著的

算法分析

燈泡開(kāi)始是關(guān)閉狀態(tài)。奇數(shù)次輪以后,為開(kāi)啟狀態(tài);偶數(shù)次輪后為關(guān)閉狀態(tài)。因此本題也就是轉(zhuǎn)化為尋找小于等于n的數(shù)的因數(shù)的個(gè)數(shù)為奇數(shù)的情況。只有平方數(shù)的因數(shù)為奇數(shù)個(gè)
例如:6的因數(shù)為1,6,2,3;而9的因數(shù)為1,9,3;

Java代碼

public class Solution {
    public int bulbSwitch(int n) {
        if(n <= 0) return 0;
        
        return (int)Math.sqrt(n);//本題最后轉(zhuǎn)化為求小于等于n的平方數(shù)的個(gè)數(shù)
    }
}

參考

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,260評(píng)論 0 23
  • 每個(gè)人的生命中,朋友大概都是很重要的一部分吧!我們那么在乎朋友,卻又不可避免的會(huì)傷害到朋友,同時(shí)也會(huì)被朋友傷害。 ...
    小小蘭Cassie閱讀 512評(píng)論 0 0
  • 1.進(jìn)程 系統(tǒng)中正在運(yùn)行的應(yīng)用程序每個(gè)進(jìn)程之間是相互獨(dú)立的,運(yùn)行在各自獨(dú)有且受保護(hù)的內(nèi)存中 2.線程 1.進(jìn)程是不...
    GSChan閱讀 478評(píng)論 0 2
  • Java基本數(shù)據(jù)類型 程序設(shè)計(jì)語(yǔ)言本質(zhì)上是一種語(yǔ)言,它是人與計(jì)算機(jī)進(jìn)行交流的媒介,使用程序語(yǔ)言編寫程序的目的是讓計(jì)...
    ZmlLucky閱讀 766評(píng)論 1 1
  • 昨晚終于把過(guò)去漏掉三天日間記錄補(bǔ)上;本來(lái)想整理下《萬(wàn)能鑰匙》觀后感,但看了別人的影評(píng)之后反倒無(wú)從下手了,想通過(guò)思維...
    二石兄閱讀 251評(píng)論 0 1

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