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.
思路
可以考虑暴力求解,枚举每轮的操作,最后统计ON的个数,这样既简单也直观,问题就是复杂度为O(n^2+n).题主考虑到的使用约数个数来判断最终状态,因为每一个约数代表当前状态会被改变一次,这样偶数次为off,奇数为ON,很容易就把复杂度降为了O(N),实现代码如下:
代码实现
int bulbSwitch1(int n) {
if(n==0)
return 0;
vector<int> blit(n,0);
int res=n;
int i=1;
while(i<=n){
int num = yue(i);
if(num%2 == 0)
--res;
++i;
}
return res;
}
//约数个数
int yue(int n){
int res = 2;
int sq = floor( sqrt(n * 1.0) + 0.5 ) ; // 0.5 为修正浮点数误差
for (int j = 2; j <= sq; j++) {
if (n % j == 0) { // 能整除则加2,因为有前后两个约数
res += 2;
}
}
if (sq * sq == n) {
--res;
}
return res;
}
上述方法是正确的,但是还是无法满足题意要求,超过99999就会出现超时,下面是改进的代码,解释可以参考注释。
int bulbSwitch(int n){
/*
考虑一下约数的方法,只有约数个数为奇数才能为on,但凡sqrt(n)*sqrt(n)!=n的数,约数个数都为偶数,
证明很简单,其他因子都是成对出现,只有为平方的时候,只有一个数。
题意变为求n以内的完全平方。
*/
return sqrt(n);
}