LeetCode 319 Bulb Switcher
2016-05-02 17:53
232 查看
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:
题意:现有n个灯泡,默认都是关闭的。第一轮会打开所有的灯泡,第二轮关闭所有偶数次序的灯泡,第三轮翻转所有次序为三的倍数位置的灯泡,直到第n轮拨动最后一个灯泡的开关。试确定第n轮后还有几盏灯是亮的。
思路和解法:
1.标号为k的灯,它是on或者off,取决于它的因子个数是奇数还是偶数;如果k的因子总数为奇数个,那么最后它是on的,如果是偶数,那么最后是off的。
2.如果k的因子总数是奇数个,那么k一定是某个数的平方。因为因子一般都是成对出现的,被平方的那个数才可以单个出现。比如36=1*36=2*18=3*12=4*9=6*6,36的因子为1,2,3,4,6,9,12,18,36,其中1*36=2*18=3*12=4*9,都是成对出现的,6和6一样,因此只出现一次,所以最后36的因子总数为奇数。36是6的平方。
3.n个灯,这样操作n次,最后状态为on的灯,标号是1*1,2*2,3*3,4*4……k*k……m*m的灯,m*m<=n。状态on的灯总数为m个。m就是n的平方根的整数部分。
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:
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.
题意:现有n个灯泡,默认都是关闭的。第一轮会打开所有的灯泡,第二轮关闭所有偶数次序的灯泡,第三轮翻转所有次序为三的倍数位置的灯泡,直到第n轮拨动最后一个灯泡的开关。试确定第n轮后还有几盏灯是亮的。
思路和解法:
1.标号为k的灯,它是on或者off,取决于它的因子个数是奇数还是偶数;如果k的因子总数为奇数个,那么最后它是on的,如果是偶数,那么最后是off的。
2.如果k的因子总数是奇数个,那么k一定是某个数的平方。因为因子一般都是成对出现的,被平方的那个数才可以单个出现。比如36=1*36=2*18=3*12=4*9=6*6,36的因子为1,2,3,4,6,9,12,18,36,其中1*36=2*18=3*12=4*9,都是成对出现的,6和6一样,因此只出现一次,所以最后36的因子总数为奇数。36是6的平方。
3.n个灯,这样操作n次,最后状态为on的灯,标号是1*1,2*2,3*3,4*4……k*k……m*m的灯,m*m<=n。状态on的灯总数为m个。m就是n的平方根的整数部分。
public int bulbSwitch(int n) { return (int) Math.sqrt(n); }
相关文章推荐
- This 指针
- C++计算每个字符出现的次数
- XMG
- 51nod #13 D 【DP】【生成函数】
- Python数据类型之列表
- Dubbo架构设计详解
- 设计模式C++学习笔记之十(Strategy策略模式)
- JSON数据格式
- 支付宝SDK快速入口链接
- 全局事务与本地事务的区别应用
- 变限积分的求导公式_20160426
- PHP命名空间的理解
- 设计模式C++学习笔记之九(Proxy代理模式)
- 分析linux内存管理机制
- scala学习(3)——函数的定义和使用
- Linux 0.11中进程睡眠和唤醒机制思考
- 1.django笔记之django基础
- Dubbo之旅--注册中心
- 比较带积分号和不带积分号的两种方法_20160423
- java基础-内部类