zoukankan      html  css  js  c++  java
  • 319. Bulb Switcher

    问题:

    给定n个初始状态为off的灯,

    • 第1次,按 1*i 号灯的开关。
    • 第2次,按 2*i 号灯的开关。
    • ...
    • 第n次,按 n 号灯的开关。

    求最后on的灯共有几个。

    Example 1:
    Input: n = 3
    Output: 1
    Explanation: At first, the three bulbs are [off, off, off].
    After the first round, the three bulbs are [on, on, on].
    After the second round, the three bulbs are [on, off, on].
    After the third round, the three bulbs are [on, off, off]. 
    So you should return 1 because there is only one bulb is on.
    
    Example 2:
    Input: n = 0
    Output: 0
    
    Example 3:
    Input: n = 1
    Output: 1
     
    Constraints:
    0 <= n <= 10^9
    

      

    解法:math

    根据题意:

    我们观察:第n号灯,被按下开关的次数=

    第 n的因数 轮。

    ex:

    • n=6:
      • 第1,2,3,6轮
    • n=9:
      • 第1,3,9轮

    这样有一个规律

    • 基本n的因数的个数都是成对的,如 1*6, 2*3, 1*9
    • 除非n是一个平方数,使得其中一个因数^2=他自己,这个因数单独存在。如 3*3

    对于开关的特性:

    • 开奇次开关:最后灯是亮的。on
    • 开偶次开关:最后灯是暗的。off

    那么我们要求的就是,存在奇数个因数的灯的个数。

    即n以内,有多少个平方数。

    sqrt(n);

    n的平方根是多少,那么从1~这个平方根,有多少个数,就存在多少个n以内的平方数。

    代码参考:

    1 class Solution {
    2 public:
    3     int bulbSwitch(int n) {
    4         return (int)sqrt(n);
    5     }
    6 };
  • 相关阅读:
    Ubuntu20 修改网卡名称
    单臂路由实现不同vlan间通信
    配置trunk和access
    基于端口划分vlan
    Zabbix5.0服务端部署
    搭建LAMP环境部署opensns微博网站
    搭建LAMP环境部署Ecshop电商网站
    Zabbix 监控过程详解
    Zabbix agent端 配置
    Zabbix 监控系统部署
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14636712.html
Copyright © 2011-2022 走看看