【LeetCode-63】Bulb Switcher

本文探讨了一个经典的灯泡开关问题,给出了简洁的解决方案,并通过数学分析揭示了为什么最终亮着的灯泡数量正好是总灯泡数目的平方根向下取整。

摘要生成于 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 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开方后向下取整的得数。

 * 下面我来解释一下。对于每个数字来说,除了平方数,都有偶数个因数。
 * 如5有2个因数:1 * 5 = 5
 * 如10有4个因数:1 * 10 = 10,2 * 5 = 10
 * 可以看出,非平方数的因数总是成对出现的,只有平方数的因数才是奇数,因为平方数除平方根外,其他的因数都是成对出现的!
 * 对于当前的开关灯泡问题,可知到最后处在平方数位置的灯泡一定是开启的,其他位置的灯泡一定是关闭的。

 * 而要计算一个数之下有多少小于或等于它的平方数,使用一个开平方用的函数就可以了

public class BulbSwitcher {
	public int bulbSwitch(int n) {
		return (int)(n > 0 ? Math.sqrt(n) : 0);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值