ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

319. Bulb Switcher

2021-04-09 13:33:10  阅读:227  来源: 互联网

标签:bulbs 319 off Switcher three 开关 因数 Input Bulb


问题:

给定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 };

 

标签:bulbs,319,off,Switcher,three,开关,因数,Input,Bulb
来源: https://www.cnblogs.com/habibah-chang/p/14636712.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有