您的位置:首页 > 其它

【leetcode】319. Bulb Switcher

2016-07-26 20:22 330 查看
一、题目描述

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.

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.


题目解读:给出一个数n 表示有n个灯泡,要进行n此操作。

第1次操作:n个灯全亮

第2次操作:每隔2个灯切换第2个灯的状态,比如一开始是 on on on on on,那么操作后变成 on off on off on

第3次操作:每隔3个灯切换第3个灯的状态

.....

第n次操作:每隔n个灯切换第n个灯的状态

例如 n=7

第1次: on on on on on on on

第2次:on off on off on off on

第3次:on off off off on on on

第4次:on off off on on on on

第5次:on off off on off on on

第6次:on off off on off off on

第7次:on off off on off off off

思路:最开始发现的规律就是,经过偶数次切换的灯泡是on,经过奇数次切换的灯泡是off,所以要算出偶数次切换的灯泡个数。而第i个灯泡的切换次数正好是 i 的因子数(不包括1,但包括 i 本身),因此问题转化为算i 的因子个数。一开始写的代码如下:

class Solution {
public:
//求n的因子个数(不包括1,但包含n本身)
int factor_num(int n){
int num=0;
for(int i=1; i<n; i++){
if(n%i == 0)  //能除断
num++;
}
return num;
}

int bulbSwitch(int n) {
int result=0;
for(int i=1; i<=n; i++){
if(factor_num(i)%2==0)
result++;
}//for
return result;
}
};


一提交告诉我超时:Time Limit Exceeded

后来谷歌别人的解法,发现这里面还有一个特别特别大的规律,那就是。。。。。对于第 i 个灯泡,如果i 是个完全平方数,那么该灯泡是on的状态。一行代码就可以搞定了。呵呵呵呵。。。。。

c++代码(0ms,10.54%)

class Solution {
public:
int bulbSwitch(int n) {
return sqrt(n);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: