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内容请搜索靠谱客的其他文章。
发表评论 取消回复