LeetCode 319 Bulb Switcher(数学Tricks)
来源:互联网 发布:中国股市知乎 编辑:程序博客网 时间:2024/06/05 12:40
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.
题目大意:有n个初始状态关闭的灯泡,第1轮操作按下编号是1的倍数的灯泡开关,第2轮操作按下编号是2的倍数的灯泡开关,第3轮操作按下编号是3的倍数的灯泡开关……第n轮操作按下编号是n的倍数的灯泡开关。问最后有几个灯泡是开着的。
解题思路:第一眼看到这道题,心想肯定是模拟,瞎敲一顿AC之后逛讨论区,发现了一个非常亮眼的解法,而且只用了一行代码。
翻译:n轮操作完成之后一个灯泡还开着,当且仅当它被按了奇数次开关。将灯泡从1到n编号,灯泡i的开关在第d轮被按下当且仅当d整除i,即灯泡i的最终状态为打开当且仅当i有奇数个因子。一般来说,因子都是成对出现的,例如当i=12时,它的因子有1和12,2和6以及3和4;只有当i是某个数的平方时,它的因子个数才是奇数个,比如i=36时,它的因子有1和36,2和18,4和9以及6,所以灯泡i的最终状态为打开当且仅当它是某个数的平方。所以我们只要统计出平方数有多少就可以。令R=int(sqrt(n)),则R是区间[1,n]内最大平方数的根,1是区间[1,n]内最小平方数的根。所以从1到R就是R个平方数的根,即答案为int(sqrt(n))。
代码如下:
int bulbSwitch(int n) { return sqrt(n);}
- LeetCode 319 Bulb Switcher(数学Tricks)
- leetcode:数学:Bulb Switcher(319)
- leetcode:数学:Bulb Switcher(319)
- leetcode 319 Bulb Switcher
- Leetcode-319 Bulb Switcher
- 【LEETCODE】319-Bulb Switcher
- LeetCode 319 Bulb Switcher
- leetcode 319 Bulb Switcher
- Leetcode 319 : Bulb Switcher
- LeetCode-319:Bulb Switcher
- LeetCode[319] Bulb Switcher
- leetcode 319 - Bulb Switcher
- LeetCode 319 Bulb Switcher
- LeetCode 319 -Bulb Switcher ( JAVA )
- LeetCode--No.319--Bulb Switcher
- LeetCode #319 - Bulb Switcher - Medium
- LeetCode:319. Bulb Switcher(C版本)
- LeetCode 319. Bulb Switcher(灯泡)
- 从需求到界面你应该注意什么
- 【链表】删除一个无头单链表的非尾节点 以及从尾到头打印单链表
- vue数组中数据变化但是视图没有更新解决方案
- 安装PyCharm新建项目出现No Python interpreter selected解决方法
- DevOps定义基础入门及历史
- LeetCode 319 Bulb Switcher(数学Tricks)
- 理解Java对象序列化
- Mysql数据库的备份与恢复
- 仿今日头条“关注”按钮的实现
- CentOS 7 下如何安装使用Composer
- 3.2的urllib.request在2.7版本的哪
- hdu 1595 find the longest of the shortest(spfa)(存储并枚举最短路径的边)
- CCNA一些基本命令
- 匹配字符串-正则表达式