zoukankan      html  css  js  c++  java
  • 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 i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

    Example:

    Input: 3
    Output: 1 
    Explanation: 
    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.

    解题思路:

    一开始我想用bool值来表示是否开着灯,然后循环并且按要求开关,但是这里没有限制n的大小,我觉得可能会超时。

    然后我点开了tag,发现是math,果然,事情没有那么简单ಠ_ಠ

    开关规则是在第i次将每i个灯的状态调反。

    i = 1时,所有灯都调反

    i = 2时,所有2的倍数的灯都状态置反

    i = 3时,所有3的倍数的灯都状态置反

    灯1:  1 2 3

    灯2:  2 

    灯3: 3

    2的因子:1, 2

    3的因子:1,3

    若有灯4: 改变该灯的i为1 2 4

    1*4 = 4 2*2 = 2

    所以平方数是亮着的,因为他们会有一个x2的因子对,这时只能改变一次。

    代码:

    class Solution {
    public:
        int bulbSwitch(int n) {
            int ret = 1;
            while(ret*ret <= n)
                ret++;
            return ret-1;
        }
    };
  • 相关阅读:
    前端学习:html基础学习四
    前端学习:html基础学习三
    cogs 2691. Sumdiv
    cogs 421. HH的项链
    Bzoj 2038: [2009国家集训队]小Z的袜子(hose)
    【NOIP模拟赛】密码锁
    cogs1612. 大话西游
    cogs1583. [POJ3237]树的维护
    Bzoj 3343: 教主的魔法
    SPOJ375 Query on a tree
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9222523.html
Copyright © 2011-2022 走看看