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;
        }
    };
  • 相关阅读:
    Python·安装扩展包的几种方法
    Arduino系列硬件资源介绍
    树莓派USB摄像头的使用
    树莓派frp服务器和客户端配置教程
    树莓派frp内网穿透
    用Windows远程桌面连接树莓派的方法
    控制窗体的位置和大小
    树霉派更换软件镜像源
    I2C的库函数应用示例
    I2C总线的Arduino库函数
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9222523.html
Copyright © 2011-2022 走看看