问题描述
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个灯泡,一开始全是灭的。第一轮将所有的灯泡都打开;第2轮将偶数号灯泡开的关掉,关的打开;第3轮将3的倍数的灯泡开的关掉,关的打开……一直到第n轮。求最后亮的灯泡的数量。
这是一道数学题,只有有整数平方根的灯泡最后才是亮着的,因为平方根的存在,其余情况均会被对应的乘数打开又关闭,而平方根只操作一次,故最终被点亮。
以36为例,它的约数有:1 * 36;2 * 18;3 * 12;4 * 9;6 * 6。所以最终是亮的。
代码
class Solution {
public:
int bulbSwitch(int n) {
return sqrt(n);
}
};
时间复杂度:
O(1)
O
(
1
)
空间复杂度:
O(1)
O
(
1
)
反思
评论区爆笑系列,各种辛辣吐槽。