leetcode 319. Bulb Switcher

来源:互联网 发布:帝国cms 统计代码 编辑:程序博客网 时间:2024/06/07 13:19

题目描述

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盏灯,然后,做n次的round,在每一轮round,每隔round个数就toggle当前灯的状态,问n轮后有多少灯是亮的状态。

我们分析每盏灯最后的状态,我们知道,在每一轮这盏灯是否会改变状态跟当前的轮数有关,即,如果灯的位置刚好被round整除,就改变这盏灯的状态。也就是说,灯的位置是round的整数倍,那么n轮后,一盏灯如果改变了奇数次状态,最后的状态就是打开的状态。
我们来思考一盏灯什么时候会改变奇数次。改变奇数次,意味着灯的位置有奇数个乘积。我们知道,假设一盏灯的位置是12,那么 12 = 2*6 3*4 1*12这几种乘积形式,在12轮后一定是改变了偶数次。上面的例子可以发现,除了幂次数外,其它的数都有偶数个乘积表示,也就是说,只要是幂次数,最后一定是有奇数次改变的。我们成功把问题转换成了找1-n中幂次数的个数,而这个问题,只需要对n开根号就可以解答,所以本题最终的答案是:

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

可以看到,本题的关键是意识到灯位置与round的关系,并利用数的性质求解,还是非常巧妙的。