<LeetCode OJ> 319. Bulb Switcher

Total Accepted: 20000  Total Submissions: 48830  Difficulty: Medium

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.

分析:

数学智力题!
本文参考,http://blog.csdn.net/Xiaohei00000/article/details/50792058
题目意思是有n(编号为1~n)个小灯,初始时候都是off状态,然后经过n次翻转,求最后状态为on的小灯的个数。
翻转过程为:
第1次:将所有小灯翻转为on状态;
第2次:将所有序号为2的倍数的小灯反转状态;
第3次:将所有序号为3的倍数的小灯反转状态...................
第i次:将所有序号为i的倍数的小灯反转状态;
第n次:将所有序号为n的倍数的小灯反转状态。
确定信息:n个灯,n次翻转。
经过分析过程可以知道,第i个小灯只有在其约数时候才反转状态,比如第16号小灯,在第1 、2、4、8、16次时候才会被反转过状态,即反转过五次,因为初始后off,所以5次后为on。比如第12号小灯,在第1、2、3、4、6、12次时候反转,即反转过6次,最终为off状态。
所以,可以根据每个小灯编号的约数的个数(奇数或者偶数)来判断该编号等的反转过几次,确定其最终的状态。
最后我们知道,每个数字的约数个数不是为偶数,就是为奇数,而只有这个数为可以开方的时候约数个数才为偶数。
所以我们只要找到n数中所有的可以开方的数的个数即可。

class Solution {
public:
    int bulbSwitch(int n) {
        //只要是<=n的平方数,它的最终状态一定是关着的
        int result=0;
        for(int i=1;i*i<=n;i++)
            result++;
        return result;    
    }
};

其实可以知道,小于等于n的平方数个数为sqrt(n)个;

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


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51559965

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值