【Leetcode】Bulb Switcher

这道LeetCode题目是关于灯泡开关的,初始所有灯泡关闭。每轮操作中,按照编号依次进行切换。第n轮时,只切换第n个灯泡。问题在于经过n轮后有多少灯泡是亮的。解题关键在于发现,灯泡是否亮取决于其约数个数的奇偶性。若约数个数为偶数,则最终灯泡保持亮的状态;若为奇数,则灯泡关闭。因此,我们需要找到小于等于n的所有完全平方数的数量,这是亮着的灯泡总数。

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

题目链接:https://leetcode.com/problems/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 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以内平方数个数问题,设有一数k < = n,若k有x个约数,则遍历的过程中必然对k操作x次。第k个灯泡一开始是on的,若x为偶数,最后依然是on的,若x为奇数,最后一定是off的。 

问题就变成求约数是偶数的灯泡的个数。对于数N,若该数有约数B,则N/B也必定为该数的约数。当B==N/B时,N的约数为奇数个,N=B*B,即N为完全平方数。 问题转化成求N以内完全平方数的个数。在1<=k<=n中,只有第1^2、2^2、3^2、4^2……m^2<=n个灯泡为on,m也就是要求的为on的灯泡总数,m<=n的平方根,即对N开方向下取整。java对double类型向int转化正好是向下取整。

算法:

public int bulbSwitch(int n) {
		return (int)Math.sqrt(n); 
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值