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 i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Input: 3
Output: 1
Explanation:
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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bulb-switcher
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
如果一个数字的所有因子是偶数,那么灯是关的,如果是奇数,及时开的。那么,只有平方数,因子才是奇数。那么结果就是这个数小的所有平方数的个数。
class Solution {
public int bulbSwitch(int n) {
int res = 1;
while (res * res <= n) ++res;
return res - 1;
}
}
也可以直接取开方。
class Solution {
public int bulbSwitch(int n) {
return (int) Math.sqrt(n);
}
}
本文探讨了一个有趣的数学问题,即灯泡开关问题。通过n轮操作后,如何确定有多少盏灯是亮着的。文章揭示了只有平方数的灯泡会保持开启状态,并提供了两种高效算法来解决这一问题。
905

被折叠的 条评论
为什么被折叠?



