【LeetCode从零单刷】Bulb Switcher
2015-12-19 16:50
399 查看
题目:
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:
解答:
我们知道,每当灯泡会改变状态,也就是 toggle 时,是因为它出现在了某个数的整数倍上。
对于第1个灯泡:1*1,会改变1次状态,即 off -》on
对于第2个灯泡:1*2,2*1,会改变2次状态,即 off -》on -》off
对于第3个灯泡:1*3,3*1,会改变2次状态,即 off -》on -》off
对于第4个灯泡:1*4,2*2,4*1,会改变3次状态,即 off -》on -》off -》on
……
会发现,每当我找到一个数的整数倍,总会找到对称的一个整数倍,例如 1*2,就肯定会有一个 2*1。唯一的例外出现在平方数上,例如 4 = 2*2,只有一次整数倍。
每次作为偶数次整数倍,最终的灯泡都会还原为 off;只有作为奇数次整数倍,最终的灯泡都会 on。
也就是说,最终亮的灯泡数目由小于其的最大平方数确定。代码非常简单:
class Solution {
public:
int bulbSwitch(int n) {
return (int)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.
解答:
我们知道,每当灯泡会改变状态,也就是 toggle 时,是因为它出现在了某个数的整数倍上。
对于第1个灯泡:1*1,会改变1次状态,即 off -》on
对于第2个灯泡:1*2,2*1,会改变2次状态,即 off -》on -》off
对于第3个灯泡:1*3,3*1,会改变2次状态,即 off -》on -》off
对于第4个灯泡:1*4,2*2,4*1,会改变3次状态,即 off -》on -》off -》on
……
会发现,每当我找到一个数的整数倍,总会找到对称的一个整数倍,例如 1*2,就肯定会有一个 2*1。唯一的例外出现在平方数上,例如 4 = 2*2,只有一次整数倍。
每次作为偶数次整数倍,最终的灯泡都会还原为 off;只有作为奇数次整数倍,最终的灯泡都会 on。
也就是说,最终亮的灯泡数目由小于其的最大平方数确定。代码非常简单:
class Solution {
public:
int bulbSwitch(int n) {
return (int)sqrt(n);
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性
- C++ Custom Control控件向父窗体发送对应的消息