我是靠谱客的博主 无限大炮,这篇文章主要介绍[LeetCode 319] Bulb Switcher,现在分享给大家,希望可以做个参考。

Question

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.

Explanation

A bulb ends up on iff it is switched an odd number of times.
A bulb is switched an odd number of times iff it has an odd number of divisors.
The normal number has an even number of divisors.
The square number has an odd number of divisors. That is because it has two same divisors.
We should calculate how many square numbers are less than or equal to n.

Code

复制代码
1
2
3
4
5
public class Solution { public int bulbSwitch(int n) { return (int)Math.sqrt(n); } }

转载于:https://www.cnblogs.com/Victor-Han/p/5157428.html

最后

以上就是无限大炮最近收集整理的关于[LeetCode 319] Bulb Switcher的全部内容,更多相关[LeetCode内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(111)

评论列表共有 0 条评论

立即
投稿
返回
顶部