Bulb Switcher燈泡開關問題----Medium

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 n rounds.

有N個燈泡初始化爲off,第一輪讓所有燈泡都變爲on,第二輪讓每次第二個的燈泡變爲off,第三輪讓每個第三個燈泡改變原來狀態(原來是off改爲on,原來是on改爲off)。第N輪,你只用改變最後一個燈泡。求在N輪後有多少燈泡是on狀態。

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=4

初始化,四個燈泡 [on, on ,on ,on]

第一輪,四個燈泡 [off, off ,off ,off]

第二輪,四個燈泡 [on, off ,on ,off]

第三輪,四個燈泡 [on, off ,off ,off]

第四輪,四個燈泡 [on, off ,off ,on]

答案:根據分析

1~3 => 1

4~8 => 2

9~15 => 3

16~24 =>4

規律是平方根

int bulbSwitch(int n) {
   return sqrt(n);
}

摘自:https://leetcode.com/problems/bulb-switcher/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章