[Swift]LeetCode319. 燈泡開關 | Bulb Switcher

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-pruwlcqa-kk.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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 i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.git

Example:github

Input: 3
Output: 1 
Explanation: 
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.

初始時有 個燈泡關閉。 第 1 輪,你打開全部的燈泡。 第 2 輪,每兩個燈泡你關閉一次。 第 3 輪,每三個燈泡切換一次開關(若是關閉則開啓,若是開啓則關閉)。第 i 輪,每 個燈泡切換一次開關。 對於第 輪,你只切換最後一個燈泡的開關。 找出 輪後有多少個亮着的燈泡。微信

示例:spa

輸入: 3
輸出: 1 
解釋: 
初始時, 燈泡狀態 [關閉, 關閉, 關閉].
第一輪後, 燈泡狀態 [開啓, 開啓, 開啓].
第二輪後, 燈泡狀態 [開啓, 關閉, 開啓].
第三輪後, 燈泡狀態 [開啓, 關閉, 關閉]. 

你應該返回 1,由於只有一個燈泡還亮着。

8ms
 1 class Solution {
 2     func bulbSwitch(_ n: Int) -> Int {
 3 
 4         if n == 0 {
 5             return 0
 6         }
 7         var i = 1
 8         while(i+1)*(i+1) <= n {
 9             i += 1;
10         }
11         return i;
12     }
13 } 

16mscode

1 class Solution {
2     func bulbSwitch(_ n: Int) -> Int {
3         var i = 0
4         while ( (i + 1) * (i + 1) <= n ) {
5             i += 1
6         }
7         return i
8     }
9 }

20mshtm

1 class Solution {
2     func bulbSwitch(_ n: Int) -> Int {
3         return Int(sqrt(Double(n)))
4     }
5 }
相關文章
相關標籤/搜索