319. Bulb Switcher&&程序员面试金典6.6
来源:互联网 发布:linux如何更改用户权限 编辑:程序博客网 时间:2024/04/28 18:28
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 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.
Subscribe to see which companies asked this question
太机智
https://leetcode.com/discuss/75014/math-solution
要解决这个问题,我们必须弄清楚所谓的“切换灯泡开关状态”是什么意思。
1.问题:灯泡会在哪几轮切换状态(开或关)?
灯泡n会在n的每个因子(包括1和n本身)对应的那一轮切换状态。也就是说,灯泡15会在第1,3,5,15轮切换状态。
2.问题:灯泡在什么时候还是亮着的?
如果因子的个数是奇数,则这个灯泡是亮着的。
3.问题:因子个数什么时候是奇数?
完全平方数的因子个数是奇数。
4.问题:有多少个完全平方数?
sqrt(n)个。
对于每一个灯泡,当它被开关奇数次时,它最终会是亮的。
将这些灯泡记为灯泡1—灯泡n。灯泡i在第d轮是会被开关当且仅当d可以整除i。所以灯泡i最终是亮着的当且仅当它有奇数个因子。
因子都是成对儿出现的,比如对i=12 有因子1和12,2和6,3和4,除当i是个平方数,例如i=36有因子1和36,2和18,3和12,4和9以及重因子6。所以灯泡i最终是亮着的当且仅当i是平方数。
所以只需要计算平方数的个数。
令R=int(sqrt(n)),它是序列[1,..,n]中最大的平方数的平方根,1是最小的平方根。所以我们就有了从1到R,也就是R个平方根,这就对应着R个平方数。所以R=int(sqrt(n))就是结果。
class Solution {public: int bulbSwitch(int n) { return sqrt(n); }};
- 319. Bulb Switcher&&程序员面试金典6.6
- 319. Bulb Switcher && 672. Bulb Switcher II
- [leetcode] 319. Bulb Switcher
- 319. Bulb Switcher
- leetcode 319. Bulb Switcher
- 319. Bulb Switcher LeetCode
- LeetCode 319. Bulb Switcher
- 319. Bulb Switcher
- 319. Bulb Switcher
- 319. Bulb Switcher
- LeetCode *** 319. Bulb Switcher
- [leetcode]319. Bulb Switcher
- 319. Bulb Switcher
- 319. Bulb Switcher
- leetcode-319. Bulb Switcher
- leetcode 319. Bulb Switcher
- 319. Bulb Switcher #Medium
- leetcode 319. Bulb Switcher
- mysql-增删改查1
- Oracle基础-建表语句(DDL)
- 字符串有结束符\0
- SPSS学习笔记之——OR值与RR值
- servlet基本配置
- 319. Bulb Switcher&&程序员面试金典6.6
- altium designer 3d元件库制作
- urllib2自定义opener详解
- 【UI基础】——提示框和警示框的实现
- 自定义ListView+.9图实现聊天界面。
- 内存管理细节1
- Android倒计时器CountDownTimer
- nyoj 305 表达式求值
- 【图像基础】局部特征点的理解