LeetCode 题解工作台
灯泡开关
初始时有 n 个灯泡处于关闭状态。第一轮,你将会打开所有灯泡。接下来的第二轮,你将会每两个灯泡关闭第二个。 第三轮,你每三个灯泡就切换第三个灯泡的开关(即,打开变关闭,关闭变打开)。第 i 轮,你每 i 个灯泡就切换第 i 个灯泡的开关。直到第 n 轮,你只需要切换最后一个灯泡的开关。 找出并返回 …
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数学·结合·brainteaser
答案摘要
我们不妨将 个灯泡编号为 $1, 2, 3, \cdots, n$,那么对于第 个灯泡,它会在第 轮被操作,当且仅当 是 的因子。 对于一个数 ,它的因子个数是有限的,且因子个数为奇数时,最后的状态是开启的,否则是关闭的。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·brainteaser 题型思路
题目描述
初始时有 n 个灯泡处于关闭状态。第一轮,你将会打开所有灯泡。接下来的第二轮,你将会每两个灯泡关闭第二个。
第三轮,你每三个灯泡就切换第三个灯泡的开关(即,打开变关闭,关闭变打开)。第 i 轮,你每 i 个灯泡就切换第 i 个灯泡的开关。直到第 n 轮,你只需要切换最后一个灯泡的开关。
找出并返回 n 轮后有多少个亮着的灯泡。
示例 1:

输入:n = 3 输出:1 解释: 初始时, 灯泡状态 [关闭, 关闭, 关闭]. 第一轮后, 灯泡状态 [开启, 开启, 开启]. 第二轮后, 灯泡状态 [开启, 关闭, 开启]. 第三轮后, 灯泡状态 [开启, 关闭, 关闭]. 你应该返回 1,因为只有一个灯泡还亮着。
示例 2:
输入:n = 0 输出:0
示例 3:
输入:n = 1 输出:1
提示:
0 <= n <= 109
解题思路
方法一:数学
我们不妨将 个灯泡编号为 ,那么对于第 个灯泡,它会在第 轮被操作,当且仅当 是 的因子。
对于一个数 ,它的因子个数是有限的,且因子个数为奇数时,最后的状态是开启的,否则是关闭的。
因此,我们只需要找到 到 中因子个数为奇数的数的个数即可。
对于一个数 ,如果它有因子 ,那么它一定有因子 ,因此因子个数为奇数的数一定是平方数。
举个例子,数字 的因子有 ,因子个数为 ,是偶数;而对于数字 这个平方数,因子有 ,因子个数为 ,是奇数。
因此,我们只需要找到 到 中有多少个平方数即可,即 。
时间复杂度 ,空间复杂度 。
class Solution:
def bulbSwitch(self, n: int) -> int:
return int(sqrt(n))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) because only the integer square root calculation is needed. Space complexity is O(1) as no additional storage is required for tracking bulb states. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Expect candidates to identify the divisor pattern instead of iterating through rounds.
- question_mark
Look for recognition that only perfect squares have an odd number of factors.
- question_mark
Candidates may attempt simulation first, signaling partial understanding of the toggle logic.
常见陷阱
外企场景- error
Simulating each round leads to timeouts for large n values.
- error
Failing to connect bulb toggles with number of divisors results in incorrect counting.
- error
Misinterpreting the pattern and counting all bulbs rather than just perfect squares.
进阶变体
外企场景- arrow_right_alt
Modify the problem to count bulbs off after n rounds instead of on, still relying on perfect square logic.
- arrow_right_alt
Introduce multiple toggle sequences with different step sizes to test mathematical generalization.
- arrow_right_alt
Consider circular bulb arrangements where toggles wrap around, requiring adjusted divisor logic.