319. Bulb Switcher

原创 2016年08月31日 14:59:57

题目

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.
分析

只有被开关奇数次的灯泡最后能够保持开启状态,故对每个灯泡i来说,如果当前趟数j能整除灯泡的编号i,那么i就会被开关一次,由于能整除i的数字都是成对出现,比如对5来说有1和5,对6有1和6,2和3,只有对平方数而言,整除它的数会出现两个数字相同的情况,这样的话就会出现被奇数次开关,比如对4而言,能整除它的有1和4,还有2,所以只需要找到n以内的完全平方数的个数即可,对n开方取整可以做到这一点,参考自Math solution

class Solution {
public:
    int bulbSwitch(int n) {
        return sqrt(n);
    }
};


相关文章推荐

leetcode 319 Bulb Switcher

leetcode319 Bulb Switcher题目描述 There are n bulbs that are initially off. You first turn on all the ...

Leetcode 319. Bulb Switcher

Bulb Switcher好久没更新博客啦,主要是因为都没刷到什么好题,这一篇也是大大的水题,不过因为思考的过程种发生了种种有(yu)趣(chun)的故事,姑且把它当作一篇娱乐向的博文来写233 不...

319. Bulb Switcher

319. Bulb Switcher

LeetCode 319. Bulb Switcher 解题报告

LeetCode 319. Bulb Switcher 解题报告

【leetcode】319. Bulb Switcher

一、题目描述 There are n bulbs that are initially off. You first turn on all the bulbs. Then, you tur...

LeetCode319——Bulb Switcher

这是一道智商碾压的题。。。

LeetCode #319 - Bulb Switcher - Medium

ProblemThere are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn of...
  • Arcome
  • Arcome
  • 2016年12月07日 20:34
  • 213

[Leetcode] 319. Bulb Switcher

题目: There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off ...

<LeetCode OJ> 319. Bulb Switcher

Total Accepted: 20000 Total Submissions: 48830 Difficulty: Medium There are n bulbs that are in...

[Leetcode] 319. Bulb Switcher 解题报告

题目: There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn o...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:319. Bulb Switcher
举报原因:
原因补充:

(最多只允许输入30个字)