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个灯拨一次开关;
第n轮每n个灯拨一次开关;
问最后还有几个灯是亮的?


分析

图1

则不难发现第i轮开关灯涉及的开关号主要包括i*k个,k为整数;
同时,开关拨动次数为偶数时,灯泡灭;开关拨动次数为奇数时,灯泡亮;
灯牌是否亮判断的方式为该灯泡开关拨动的次数是否为奇数;
因此第n个灯泡最后是否亮取决于灯泡号的因数是否为奇数个。

对于第i个灯泡,当i的因子个数为奇数时,最终会保持点亮状态,例如9的因子为1,3,9而当i的因子个数为偶数时,最终会保持熄灭状态,例如8的因子为:1,2,4,8当且仅当i为完全平方数时,其因子个数为奇数。

为什么只有完全平方数的因子个数为奇数?因为除了完全平方数,其余数字的因子都是成对出现的,而完全平方数的平方根只会统计一次。

对n开平方并取整即可得到结果


源码

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

优化的结果:

class Solution {
public:
    int bulbSwitch(int n) {
         return (sqrt(n));  
    }
};

JavaScript:

/**
 * @param {number} n
 * @return {number}
 */
var bulbSwitch = function(n) {
    var result=Math.sqrt(n);

    return parseInt(result);
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值