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

通过以下代码可以找到规律:

#include<vector>

#include<iostream>

using namespace std;

class Solution {

public:

int bulbSwitch(int n) {

int cnt=0;

vector<int>v=vector<int>(n+1,0);

for(int i=1;i<=n;i++){

for(int j=i;j<=n;j+=i)v[j]++;

}

for(int i=1;i<=n;i++)

if(v[i]&1)cnt++;

return cnt;

}

};

int main(){

Solution test=Solution();

for(int i=1;i<=50;i++)

cout<<test.bulbSwitch(i)<<endl;

system("pause");

return 0;

}

可以看出,依次输出3个1,5个2,7个3,9个4.。。。。(如果使用以上代码,会超时)

   

在网上搜到的解题思路:

题目的意思是n个灯泡,第i次,第i*1,i*2…i*k个灯被切换,以n=6为例,

1=1×1,指第一次round

2=1×2,2×1,指第1,2次round

3=1×3,3×1,指第1,3次round

4=1×4,2×2,4×1,指第1,2,4次round

5=1×5,5×1,指第1,5次round

6=1×6,2×3,3×2,6×1,指第1,2,3,6次round

class Solution {

public:

int bulbSwitch(int n) {

return (int)sqrt(n);

}

};

 

你可能感兴趣的:(319. Bulb Switcher)