319. Bulb Switcher
2016-06-09 17:08
381 查看
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:
Analysis:
这道题等同于找出一个数的因子个数,每个因子翻转一次。当因子个数为奇数时,翻转奇数次(ON); 当为偶数时,翻转偶数次(off)。
而我们知道只有完全平方数(1,4,9….)的因子个数是奇数,因此使用sqrt(n)求出完全平方数个数即为答案。经测试,C++中int是向下取整。
Source Code(C++):
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.
Analysis:
这道题等同于找出一个数的因子个数,每个因子翻转一次。当因子个数为奇数时,翻转奇数次(ON); 当为偶数时,翻转偶数次(off)。
而我们知道只有完全平方数(1,4,9….)的因子个数是奇数,因此使用sqrt(n)求出完全平方数个数即为答案。经测试,C++中int是向下取整。
Source Code(C++):
class Solution { public: int bulbSwitch(int n) { return (int)sqrt(n); } };
相关文章推荐
- 欢迎使用CSDN-markdown编辑器
- 大学毕业4年-回顾和总结(10)-文档化战略,执行最成功的战略,堪比我人生中的“隆中对”(战略在前,成果在后)
- 大学毕业4年-回顾和总结(10)-文档化战略,执行最成功的战略,堪比我人生中的“隆中对”(战略在前,成果在后)
- 大学毕业4年-回顾和总结(10)-文档化战略,执行最成功的战略,堪比我人生中的“隆中对”(战略在前,成果在后)
- 用LaTeX写线性规划
- hadoop环境搭建
- u-boot
- leetcode-Merge k Sorted Lists-23(未完待续)
- codevs 1033 蚯蚓的游戏问题
- TC 8.52a 32位绿色精简版
- 如何在mac终端上使用python3.5
- 编解码学习笔记(一):基本概念
- 操作系统(CPU模式)习题
- tomcat启动maven依赖项目报错:java.lang.ClassNotFoundException: com.test.core.listener.ContextParameterLi
- Python 循环语句
- 电商之梳理hibernate知识---开发基框架础
- AltertDialog在DialogFragment中的使用
- Android Studio 报错总结
- HDU 2899 Strange fuction(三分)
- 【bzoj3196】【二逼平衡树】【线段树套平衡树】