[leetcode319] Bulb Switcher--判断约数的个数的奇偶性

19 篇文章 0 订阅

Question:

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~n)个小灯,初始时候都是off状态,然后经过n次翻转,求最后状态为on的小灯的个数。

翻转过程为:第1次:将所有小灯翻转为on状态;

第2次:将所有序号为2的倍数的小灯反转状态;

第3次:将所有序号为3的倍数的小灯反转状态

。。。

第i次:将所有序号为i的倍数的小灯反转状态;

第n次:将所有序号为n的倍数的小灯反转状态。


经过分析过程可以知道,第i个小灯只有在其约数时候才反转状态,比如第16号小灯,在第1 、2、4、8、16次时候反转过状态,即反转过五次,因为初始后off,所以5次后为on。比如第12号小灯,在第1、2、3、4、6、12次时候反转,即反转过6次,最终为off状态。

所以,可以根据每个小灯编号的约数的个数(奇数或者偶数)来判断反转过几次,即最终状态。

可以知道,每个数字的约数个数不是为偶数,就是为奇数,而只有这个数为可以开方的时候约数个数才为偶数。

所以我们只要找到n数中所有的可以开方的数的个数即可。


代码如下:

<span style="font-size:14px;">int bulbSwitch(int n) {
    int counts = 0;

    for (int i=1; i*i<=n; ++i) {
        ++ counts;    
    }

    return counts;
}</span>


其实可以知道,1~n之间的可以开方的个数为sqrt(n)个;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值