LeetCode 319 Bulb Switcher(数学Tricks)

来源:互联网 发布:中国股市知乎 编辑:程序博客网 时间:2024/06/05 12:40

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个初始状态关闭的灯泡,第1轮操作按下编号是1的倍数的灯泡开关,第2轮操作按下编号是2的倍数的灯泡开关,第3轮操作按下编号是3的倍数的灯泡开关……第n轮操作按下编号是n的倍数的灯泡开关。问最后有几个灯泡是开着的。

解题思路:第一眼看到这道题,心想肯定是模拟,瞎敲一顿AC之后逛讨论区,发现了一个非常亮眼的解法,而且只用了一行代码。

翻译:n轮操作完成之后一个灯泡还开着,当且仅当它被按了奇数次开关。将灯泡从1到n编号,灯泡i的开关在第d轮被按下当且仅当d整除i,即灯泡i的最终状态为打开当且仅当i有奇数个因子。一般来说,因子都是成对出现的,例如当i=12时,它的因子有1和12,2和6以及3和4;只有当i是某个数的平方时,它的因子个数才是奇数个,比如i=36时,它的因子有1和36,2和18,4和9以及6,所以灯泡i的最终状态为打开当且仅当它是某个数的平方。所以我们只要统计出平方数有多少就可以。令R=int(sqrt(n)),则R是区间[1,n]内最大平方数的根,1是区间[1,n]内最小平方数的根。所以从1到R就是R个平方数的根,即答案为int(sqrt(n))。

代码如下:

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

原创粉丝点击