Middle-题目5:319. Bulb Switcher

原创 2016年05月31日 15:27:01

题目原文:
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个灯泡,都是关闭的,你进行n轮操作:
第1轮,你把每个灯泡的状态都改变(打开的关闭,关闭的打开);
第2轮,你把每个灯泡序号是2的倍数的灯泡都改变状态(灯泡序号从1开始);
……
第i轮,你把每个灯泡序号是i的倍数的灯泡都改变状态(灯泡序号从1开始);
……
第n轮,你把最后一个灯泡改变状态(因为1~n里面n的倍数只有n)
求n轮过后,还有几个灯泡亮着?
题目分析:
若一个灯泡在n轮过后还是亮的,说明这个灯泡被改变了奇数次,因为只有被轮数整除的时候才能变状态,所以[1,k]能整除这个灯泡序号k的正整数是奇数个。
以下证明k是个完全平方数。
首先,若灯泡的序号i是平方数,则i的因数一定是奇数个,证明:
因为i是平方数,所以i=k*k,其中k∈Z,而1能整除i,所以i的因数个数为k的非1因子个数*2+1,一定是一个奇数。
那么若i不是平方数,i的因数必然是偶数个,证明:
设所有<i的因子构成的集合为A,>i的因子构成的集合为B,显然A∪B即为i的所有因子构成的集合,而对任意a∈A,必存在唯一的i/a∈B,反之亦然,所以A和B两个集合的元素个数相等。
综上证明,只有≤n的完全平方数最后是亮的。那么求i的取整即可。一行代码解决。
源码:(language : c)

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

成绩:
0ms,beats 6.36%,众数0ms,93.14%
Cmershen的碎碎念:
这道题起初只想到进行模拟,但看到discuss中给出的答案是求sqrt(n),遂想到了上述证明过程。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

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...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目5:319. Bulb Switcher
举报原因:
原因补充:

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