319. Bulb Switcher

本文探讨了一道有趣的数学问题——灯泡开关问题。通过n轮开关操作后,哪些灯泡会保持开启状态?文章揭示了只有那些有整数平方根编号的灯泡才会最终保持开启,并提供了一个简洁的C++解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

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 )


反思

评论区爆笑系列,各种辛辣吐槽。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值