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 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.
class Solution {
public:
int bulbSwitch(int n)
{
if (n == 1) return 1;
vector<bool> bulbs(n + 1, true);
for (int i = 2; i < n; i++)
{
for (int k = 1; k <= n; k++)
{
if (k % i == 0)
bulbs[k] = !bulbs[k];
}
}
bulbs[n] = !bulbs[n];
int ret = 0;
for (int k = 1; k <= n; k++)
{
if (bulbs[k]) ret++;
cout<<bulbs[k]<<" ";
}
return ret;
}
};
规律就是相隔2、4、6、8、10...个0就有一个1
class Solution {
public:
int bulbSwitch(int n)
{
int zero = 2;
int ret = 0;
int now_count = 0;
while (now_count < n)
{
now_count ++; //遇到了 1
ret ++;
now_count += zero;
zero += 2;//0的间隔加2
}
return ret;
}
};
本文探讨了灯泡切换器问题,即经过n轮开关操作后亮着的灯泡数量。通过具体示例展示了如何使用两种不同的方法解决该问题:一种是通过模拟每一轮的操作来确定最终状态;另一种则是发现并利用了灯泡状态变化的规律。
901

被折叠的 条评论
为什么被折叠?



