Bulb Switcher 题解

本文探讨了灯泡切换器问题,通过分析灯泡在不同轮次的状态变化规律,总结出只有完全平方数编号的灯泡会在最后保持开启状态。最终提供了一个简洁高效的算法解决方案。

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 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.

题目链接:319. Bulb Switcher


算法描述:

由题意知,给定 n 个灯泡,我们将进行开关转换(开->关 或 关->开),灯泡初始情况是灭的。第一次,每隔一个灯泡进行一次转换(即每个灯泡都将转换一次);第二次,每隔两个灯泡进行一次转换(即灯泡2,4,6,8……)

;第三次,每隔三个灯泡转换一次(即灯泡3,6,9,12……);……依次进行。执行完 n 次后,我们将返回开着的灯泡个数。

我们对以上进行归纳:当开关拨动次数为偶数时灯将熄灭(关),拨动次数为奇数时灯将亮起(开)。第 i 轮,灯泡是否被转换波动取决于它能否被 i 整除。1的因数有1(开);2的因数有1,2(关);3的因数1,3(关);4的因数1,2,4(开);5的因数1,5(关);6的因数1,2,3,6(关);7的因数1,7(关);8的因数1,2,4,8(关);9的因数1,3,9(开);……可以发现,完全平方数就是我们所求的。

因此我们求出不大于 n 的完全平方数的个数即可。


代码:

class Solution {
public:
    int bulbSwitch(int n) {
        int ans=0;
        for(int i=1; i*i<=n; i++){
            ans++;
        }
        return ans;
    }
};








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值