[LeetCode]-319. Bulb Switcher (Medium)(Java)
来源:互联网 发布:如何在淘宝做代理商 编辑:程序博客网 时间:2024/09/21 08:47
Total Accepted: 11921 Total Submissions: 30116 Difficulty: Medium
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:
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.
Subscribe to see which companies asked this question
Have you met this question in a real interview?
Yes
No
Discuss
中文:现有n个灯泡,默认都是关闭的。第一轮会打开所有的灯泡,第二轮关闭所有偶数次序的灯泡,
第三轮翻转所有次序为三的倍数位置的灯泡,直到第n轮拨动最后一个灯泡的开关。
试确定第n轮后还有几盏灯是亮的.
解析:
返回值其实就是n开方后向下取整的得数。
对于每个数字来说,除了平方数,都有偶数个因数。
例如:
如6有4个因数:1×6=6,2×3=6
如60有12个因数:1×60=60,2×30=60,3×20=60,4×15=60,5×12=60,6×10=60
可以看出,非平方数的因数总是成对出现的,只有平方数的因数才是奇数,因为平方数除平方根外,其他的因数都是成对出现的!对于当前的开关灯泡问题,可知到最后处在平方数位置的灯泡一定是开启的,其他位置的灯泡一定是关闭的。
而要计算一个数之下有多少小于或等于它的平方数,使用一个开平方用的函数就可以了.
public class Solution { public int bulbSwitch(int n) { return (int)Math.sqrt(n); }}
0 0
- [LeetCode]-319. Bulb Switcher (Medium)(Java)
- 319. Bulb Switcher #Medium
- LeetCode #319 - Bulb Switcher - Medium
- 319.leetcode Bulb Switcher (medium)[观察总结规律]
- [leetcode] 319. Bulb Switcher
- leetcode 319. Bulb Switcher
- 319. Bulb Switcher LeetCode
- 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
- Android 搜索 把软键盘上的回车键改为搜索
- IntelliJ IDEA 15.0 Help--Creating a Gradle Project
- OpenGL与红宝书第八版第一个程序配置
- 文本分析实例---QQ聊天记录分析
- Android--sharepreference总结
- [LeetCode]-319. Bulb Switcher (Medium)(Java)
- 放肆地用 UIBezierPath 和 CAShapeLayer 画各种图形
- Objective-C中的@property
- ijl JPEG转Yuv422
- 在C#中,不安装Oracle客户端如何连接Oracle数据库
- 在html中打出一条虚线
- MapReduce框架详解
- Android 学习 2016.03.01
- Ubuntu server 14.04.1安装TPM-emulator(成功步骤)