概述
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
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 319] Bulb Switcher所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复