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 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.


    用DP非常直观的解法如下,但是超时了。
    public int BulbSwitch(int n) {
            var dp = new bool[n+1];
            for(int i=1;i<=n;i++)
            {
                int j = 1;
                while(i*j<=n)
                {
                    dp[i*j] = !dp[i*j];
                    j++;
                }
            }
            int res=0;
            for(int i =1;i<=n;i++)
            {
                if(dp[i] == true) res++;
            }
            return res;
        }

    仔细分析,以6,16为例,6可以分解为[1,6],[2,3],[3,2],[6,1],也就是说,反复了四次,on/off不变,所以是off。只要能分解为偶数对个两个数的相乘,就是off。那什么情况下会有奇数个分解呢?只要在恰好是平方差数的时候,那么问题化简为求1-n这些数里哪些是平方差数。代码如下:

    public int BulbSwitch(int n) {
            int res=0;
            for(int i=1;i<=Math.Sqrt(n);i++)  if(i*i<=n) res++;
            return res;
        }

    更为简单的方法是只需要知道sqrt就好了。。

    public int BulbSwitch(int n) {
            return  (int)Math.Sqrt(n);
        }
  • 相关阅读:
    用内联取代宏代码
    参数的缺省值
    令人迷惑的隐藏规则
    重载与覆盖
    重载是如何实现的?
    重载的起源
    C++函数的高级特性
    使用调试器逐步跟踪程序
    new/delete 的使用要点
    malloc/free 的使用要点
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5902465.html
Copyright © 2011-2022 走看看