[leetcode] 319. Bulb Switcher

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轮的时候每1个灯拨1次开关;第2轮的时候每2个灯拨1次开关(每2个一组的第2个拨动开关);第3轮的时候每3个灯拨1次开关(每3个一组的第3个拨动开关);依次类推,第n轮的时候每n个灯泡拨一次开关(每n个一组的第n个拨动开关);当经过n轮后还有多少灯泡是亮着的。

思路:
      本题的解题方法很简单,但是必须理解题意,并且能把每轮的转换特点转化为好处理的数学模型。具体就是,每个灯泡最后会保持亮的状态就是它的开关被拨动奇数次,也就是说在n轮中开关的拨动中,它在n中的因数是奇数个,转化为数学模型不难发现,要是奇数个因子,则其中必有一个因子是它的平方根(两个因子一样相当于一个),因此此题主要就是迭代n,判断其中可以出现平方根的数的个数。

      其中一个好的博主的文章介绍此题,主要是图片很生动,容易理解,此处借鉴一下,也可以直接去原文章去看,连接如下:以下详解图片原出处
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

代码如下:

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值