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.
Approach
- 这是一道找规律题,如果直接模拟必然超时,题目大意就是当第
i
回合时,每间隔i
将灯泡反转,灯泡亮则暗,暗则亮。 - 怎么找规律呢,我将所有结果都打印了一遍发现了规律。
- 不难发现,每间隔
2
的倍数递增的灯泡亮。
Code
class Solution {
public:
int bulbSwitch(int n) {
if (n == 0)return 0;
int index = 1, cnt = 0;
for (int i = 2; index <= n; i += 2) {
cnt++;
index += (i+1);
}
return cnt;
}
};