LeetCode-319:Bulb Switcher
来源:互联网 发布:手机免费看书软件 编辑:程序博客网 时间:2024/05/29 04:01
原题描述如下:
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 aftern 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。Java代码:
public class Solution {public int bulbSwitch(int n) {
return (int)(n >= 0 ? Math.sqrt(n) : 0);
}
}
0 0
- leetcode 319 Bulb Switcher
- Leetcode-319 Bulb Switcher
- 【LEETCODE】319-Bulb Switcher
- LeetCode 319 Bulb Switcher
- leetcode 319 Bulb Switcher
- Leetcode 319 : Bulb Switcher
- LeetCode-319:Bulb Switcher
- LeetCode[319] Bulb Switcher
- leetcode 319 - Bulb Switcher
- LeetCode 319 Bulb Switcher
- LeetCode 319 -Bulb Switcher ( JAVA )
- LeetCode--No.319--Bulb Switcher
- LeetCode #319 - Bulb Switcher - Medium
- leetcode:数学:Bulb Switcher(319)
- leetcode:数学:Bulb Switcher(319)
- LeetCode 319 Bulb Switcher(数学Tricks)
- [leetcode] 319. Bulb Switcher
- leetcode Bulb Switcher
- 植物的知识
- 一个产品菜鸟的起飞之路
- Java7在数字中使用下划线
- E - Internet Service Providers
- JAVASE总结--03(方法、if-else、switch-case)
- LeetCode-319:Bulb Switcher
- 类与类间的关系
- Nordic发布用微型封装尺寸的高性能单芯片低功耗蓝牙SoC器件,瞄准可穿戴产品和空间受限的IoT应用
- 60.In which of the scenarios will the DBA perform recovery? (Choose all that apply.)
- Boundless SDK模板开发
- jQuery总结(一)
- Inno Setup使用说明
- POJ 2236 Wireless Network .
- [算法学习笔记]几个排序算法的比较