一. 题目描述
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.
二. 题目分析
题目大意是,有n只初始处于关闭状态的灯泡。你首先打开所有的灯泡(第一轮)。然后,熄灭所有序号为2的倍数的灯泡。第三轮,切换所有序号为3的倍数的灯泡(开着的就关掉,关着的就打开)。第n轮,你只切换最后一只灯泡。计算n轮之后还有几盏灯泡亮着。
先看看以下规律:
第1个灯泡:1的倍数,会改变1次状态: off -> on
第2个灯泡:1的倍数,2的倍数,会改变2次状态: off -> on -> off
第3个灯泡:1的倍数,3的倍数,会改变2次状态: off -> on -> off
第4个灯泡:1的倍数,2的倍数,4的倍数,会改变3次状态: off -> on -> off -> on
第5个灯泡:1的倍数、5的倍数,会改变2次状态: off -> on -> off
第6个灯泡:1的倍数,2的倍数,3的倍数,6的倍数,会改变4次状态: off -> on -> off -> on -> off
第7个灯泡:1的倍数、7的倍数,会改变2次状态: off -> on -> off
第8个灯泡:1的倍数,2的倍数,4的倍数,8的倍数,会改变4次状态: off -> on -> off -> on -> off
第9个灯泡:1的倍数,2的倍数,4的倍数,会改变3次状态: off -> on -> off -> on
……
通过上面的描述可以发现,对于n = 2,3,5,6,7,8
,找到一个数的整数倍,总会找到对称的一个整数倍,例如 1 * 2
,就肯定会有一个 2 * 1
。因此这些编号的灯泡会改变偶数次,最终结果肯定为off
。
只有当n = 1,4,9
这类完全平方数,有奇数次变化,最终的灯泡都会 on
。
只要能得出以上结论,用一句代码就可以解决问题。
三. 示例代码
class Solution {
public:
int bulbSwitch(int n) {
return sqrt(n);
}
};
四. 小结
对于一些组合类的算法题,找规律比直接动手实现更为重要。