Leetcode 319. Bulb Switcher

这是一个非常巧妙的题目,网站称之为brain teaser,意思就是代码写起来会非常简介(就是逗你玩:)),题目如下:

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.

第一次: 1×1 只有这一种情况,所以所有的灯泡由off --> on
第二次:2×1 1*2也就是说会有两个switch,一个是1为间隔的switch,一个是2为间隔的switch,off->on-->off
第三次:如前面所示,1×3 3×1,off-->on-->off
,,,,,

以此类推,我们发现a*b总是有b*a相对应,也就是说,有偶数个switch,这样的话,off还是off,on还是on,也就是保持不变,除了一种情况,就是3×3这种,如果sqrt(间隔)为整数,则表示有奇数次switch,会发生状态的变化,那么我们现在再考虑这个问题就很简单了,因为一开始所有的灯泡都是灭的,所以我们只需要寻找满足1.小于n,2.且sqrt为整数的个数。答案显然是sqrt(n)

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

posted on 2015-12-23 22:04  RookieCoder  阅读(522)  评论(0编辑  收藏  举报

导航