319. 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 i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

Example:

Input: 3
Output: 1 
Explanation: 
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.

解题思路:

一开始我想用bool值来表示是否开着灯,然后循环并且按要求开关,但是这里没有限制n的大小,我觉得可能会超时。

然后我点开了tag,发现是math,果然,事情没有那么简单ಠ_ಠ

开关规则是在第i次将每i个灯的状态调反。

i = 1时,所有灯都调反

i = 2时,所有2的倍数的灯都状态置反

i = 3时,所有3的倍数的灯都状态置反

灯1:  1 2 3

灯2:  2 

灯3: 3

2的因子:1, 2

3的因子:1,3

若有灯4: 改变该灯的i为1 2 4

1*4 = 4 2*2 = 2

所以平方数是亮着的,因为他们会有一个x2的因子对,这时只能改变一次。

代码:

class Solution {
public:
    int bulbSwitch(int n) {
        int ret = 1;
        while(ret*ret <= n)
            ret++;
        return ret-1;
    }
};

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9222523.html