Bulb Switcher

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.

 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个灯泡, 第一轮,将所有的灯泡都打开; 第二轮,按下所有的灯泡数为2的倍数的灯泡的开关(变成关闭) 第三轮,按下所有的灯泡数为2的倍数的灯泡的开关 ... 如此继续下去 第n轮,按下第n个灯泡的开关

分析:显然要求出第i个灯泡的状态,得知道i的所有的乘法因子的个数,如果是奇数,那么第i个灯泡的状态就是on态,如果是偶数,就是off态

如何求出一个数i的整数因子个数了,

对于i,如果i的整数因子是以sqrt(i)分开的,例如12(1, 2, 3, 4, 6, 12)
我们发现如果sqrt(i)是个整数,那么i的整数因子的个数一定是奇数,反之,为偶数,因为sqrt(i)左右的数是相互组合在一起构成12的(1,12), (2, 6), (3, 4)

对于每一个i,求出i的整数因子的个数,如果为奇数,那么将处于on状态,如果为偶数,将处于off状态,所以只需要求出1到n中所有具有基数个数的个数就ok,而我们发现只有n为平方数的时候,他才有基数个整数因子,所以在小于等于n的数中,平方数的个数就是sqrt(n)

所以只用求出从1到n中所有的是平方数的数即可,也就是sqrt(n)。

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

results matching ""

    No results matching ""