319. Bulb Switcher&&程序员面试金典6.6

来源:互联网 发布:linux如何更改用户权限 编辑:程序博客网 时间:2024/04/28 18:28

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

Subscribe to see which companies asked this question

Hide Tags
 Math Brainteaser

太机智

https://leetcode.com/discuss/75014/math-solution


要解决这个问题,我们必须弄清楚所谓的“切换灯泡开关状态”是什么意思。

1.问题:灯泡会在哪几轮切换状态(开或关)?

灯泡n会在n的每个因子(包括1和n本身)对应的那一轮切换状态。也就是说,灯泡15会在第1,3,5,15轮切换状态。

2.问题:灯泡在什么时候还是亮着的?

如果因子的个数是奇数,则这个灯泡是亮着的。

3.问题:因子个数什么时候是奇数?

完全平方数的因子个数是奇数。

4.问题:有多少个完全平方数?

sqrt(n)个。





对于每一个灯泡,当它被开关奇数次时,它最终会是亮的。


将这些灯泡记为灯泡1—灯泡n。灯泡i在第d轮是会被开关当且仅当d可以整除i。所以灯泡i最终是亮着的当且仅当它有奇数个因子。


因子都是成对儿出现的,比如对i=12 有因子1和12,2和6,3和4,除当i是个平方数,例如i=36有因子1和36,2和18,3和12,4和9以及重因子6。所以灯泡i最终是亮着的当且仅当i是平方数。


所以只需要计算平方数的个数。


令R=int(sqrt(n)),它是序列[1,..,n]中最大的平方数的平方根,1是最小的平方根。所以我们就有了从1到R,也就是R个平方根,这就对应着R个平方数。所以R=int(sqrt(n))就是结果。


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


0 0
原创粉丝点击