LeetCode:Bulb Switcher
来源:互联网 发布:nagios源码 编辑:程序博客网 时间:2024/06/05 10:31
题目描述:
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.
思路:
这是一个类似脑筋急转弯的题目。
题目翻译成数学问题就是:整数1-n中有奇数个约数的数有多少个。
如:
1的约数:1。有1个。
2的约数:1、2。有2个。
3的约数:1、3。有2个。
4的约数:1、2、4。有3个。
5的约数:1、5。有2个。
6的约数:1、2、3、6。有4个。
7的约数:1、7。有2个。
8的约数:1、2、4、8。有4个。
9的约数:1、3、9。有3个。
从中发现规律,1、4、9有奇数个约数,它们都是某个数的平方。这些编号的灯会亮着。
只要统计1-n中有多少个是一个数的平方就可以了。
这些数是,1^2,2^2,3^3,……,sqrt(n)^2.
一共是sqrt(n)个。
代码:
class Solution {public: int bulbSwitch(int n){return (int)sqrt(n);}};
0 0
- [leetcode] 319. Bulb Switcher
- leetcode Bulb Switcher
- [Leetcode]Bulb Switcher
- 【Leetcode】Bulb Switcher
- leetcode 319 Bulb Switcher
- Bulb Switcher | LeetCode
- Leetcode-319 Bulb Switcher
- Leetcode: Bulb Switcher
- leetcode 319. Bulb Switcher
- 【LEETCODE】319-Bulb Switcher
- leetcode之Bulb Switcher
- LeetCode Bulb Switcher
- LeetCode Bulb Switcher
- Leetcode: Bulb Switcher
- leetcode笔记:Bulb Switcher
- LeetCode:Bulb Switcher
- LeetCode 之 Bulb Switcher
- 319. Bulb Switcher LeetCode
- 线段是否相交问题 HDU 1086 You can Solve a Geometry Problem too
- 随机森林算法的简单总结及python实现
- gcc 编译参数 -fPIC 的详解和一些问题
- bShare分享-分享到微信、微博、QQ
- 代理总结
- LeetCode:Bulb Switcher
- libevent的安装
- 最新版 CocoaPods 的安装流程
- (二)计算机网络体系结构与参考模型
- Android Design Support Library(5)- CoordinatorLayout的入门使用
- org.hibernate.PersistentObjectException: detached entity passed to persist
- 恭喜自己获得了准博客专家
- 最长不降子序列(LIS)
- iOS 真机测试