leetcode Bulb Switcher
2015-12-20 12:44
288 查看
leetcode 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 nthround, 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.
题目地址:leetcode Bulb Switcher
题意:
给定n,初始的时候灯都是灭的,让你进行进行开关灯。第一轮的时候把1的倍数反转(原来关就开,原来开就关),第二轮把2的倍数翻转,以此类推到第n轮。
求最后灯打开的个数
思路:
我们来分析下:对于素数,那么它仅有1和它本身,最后一定是关掉的。
对一普通的,一定是关掉的,因子成对出现
对于完全平方数,因为有一个倍数不成对出现,所以一定是打开的。比如4 => 1,4 | 2
所以本题就是求1~n有几个完全平方数。
那么,怎么求呢?从1开始到n,每个数测试一下?时间复杂度O(n),太慢
正确的是直接sqrt(n),就可以算出来啦~
原文地址 http://www.hrwhisper.me/leetcode-bulb-switcher/
class Solution { public: int bulbSwitch(int n) { return sqrt(n); } };
本博客若无特殊说明则由 hrwhisper 原创发布
转载请点名出处:细语呢喃 > leetcode
Bulb Switcher
本文地址:http://www.hrwhisper.me/leetcode-bulb-switcher/
相关文章推荐
- leetcode刷题日记——Binary Tree Postorder Traversal
- 解决"is marked as crashed and should be repaired"方法
- Oracle中使用expimp时涉及的字符集问题
- mysql数据误删除(drop)的恢复. (ext3grep, extundelete)
- 《挑战程序设计竞赛》2.3 动态规划-进阶 POJ1065 1631 3666 2392 2184(5)
- 永久开启完整版Google Play
- 去掉导航栏分割线 和 设置导航栏的背景颜色
- 在腾讯云主机部署Play应用
- Leetcode: Search a 2D Matrix II
- Error400
- grub4dos和winsetupfromusb1.4
- 杂物 python (一)
- spring使用aop时需要设置proxy-target-class="true" 否则无法依赖注入
- 仁爱助学项目-jeecg开发学习
- rac安装grid报INS-41112错误
- inline函数
- sizeof既是关键字,又是运算符(操作符),但不是函数!
- js获取父子兄弟节点
- [uwp]MVVM之MVVMLight,一个登录注销过程的简单模拟
- Educational Codeforces Round 3 E (609E) Minimum spanning tree for each edge