加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[Swift]LeetCode319. 灯泡开关 | Bulb Switcher

发布时间:2020-12-14 05:06:27 所属栏目:百科 来源:网络整理
导读: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

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.

Example:

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,on].
After third round,off]. 

So you should return 1,because there is only one bulb is on.

初始时有?n?个灯泡关闭。 第 1 轮,你打开所有的灯泡。 第 2 轮,每两个灯泡你关闭一次。 第 3 轮,每三个灯泡切换一次开关(如果关闭则开启,如果开启则关闭)。第?i?轮,每?i?个灯泡切换一次开关。 对于第?n?轮,你只切换最后一个灯泡的开关。 找出?n?轮后有多少个亮着的灯泡。

示例:

输入: 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 } 

16ms

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 }

20ms

1 class Solution {
2     func bulbSwitch(_ n: Int) -> Int {
3         return Int(sqrt(Double(n)))
4     }
5 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读