LeetCode:Bulb Switcher
2016-01-17 18:47
281 查看
题目描述:
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:
思路:
这是一个类似脑筋急转弯的题目。
题目翻译成数学问题就是:整数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)个。
代码:
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); } };
相关文章推荐
- libevent的安装
- JavaScript对象与JSON
- 代理总结
- 打印数值二进制形式
- gcc 编译参数 -fPIC 的详解和一些问题
- 随机森林算法的简单总结及python实现
- c++中的引用
- Linux 高性能server编程——高级I/O函数
- 处理类型(typedef,uisng,auto,decltype)
- Oracle释放高水位线
- SGU 531. Bonnie and Clyde 线段树
- lintcode:minimum adjustment cost 最小调整代价
- 【Hyper-V】与【VirtualBox】【VMware】冲突的解决方法
- java(14)--servlet生命周期
- 虚拟机linux下安装jdk和 hadoop
- 自考心得
- centos7中mysql(mariadb)安装和启动
- 近200篇机器学习深度学习资料分享
- Android的消息处理机制 Handler Looper Message
- Android 3d云标签