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.
有n盏电灯,序号设为1,2,3,...,n,初始状态都是关闭。现在对它们进行n次操作,第i次操作的对象是序号为i,2i,3i,...的电灯,每次操作改变其状态(关闭变成打开,打开变成关闭)。求最终有多少盏电灯打开。


解法:

如果使用两层循环,提交结果是Time Limit exceeded。考虑到该问题实际上是求对于每个i(1≤i≤n),i能被多少个数整除,记为x(比如i=8,则1,2,4,8符合,8能被4个数整除),若x为偶数,该盏灯还是关闭的;反之亦然。现在再来看,一个数i,若有一个因子,必然能找到另一个因子为 i除以第一个因子的结果。只有某数是某数的平方,才为奇数。所以问题简单地归结为求sqrt(n)。

public class Solution {
    public static int bulbSwitch(int n) {
        double res = Math.sqrt(n);
        return (int)res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值