【LeetCode】319. Bulb Switcher 灯泡开关(Medium)(JAVA)
题目地址: https://leetcode.com/problems/bulb-switcher/
题目描述:
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.
Return the number of bulbs that are on after n rounds.
Example 1:
![](https://i-blog.csdnimg.cn/blog_migrate/5e7558ae3e4cc967182fd42c2e609479.jpeg)
Input: n = 3
Output: 1
Explanation: At first, the three bulbs are [off, off, off].
After the first round, the three bulbs are [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 1
Constraints:
- 0 <= n <= 10^9
题目大意
初始时有 n 个灯泡关闭。
第 1 轮,你打开所有的灯泡。 第 2 轮,每两个灯泡你关闭一次。 第 3 轮,每三个灯泡切换一次开关(如果关闭则开启,如果开启则关闭)。
第 i 轮,每 i 个灯泡切换一次开关。 对于第 n 轮,你只切换最后一个灯泡的开关。
找出 n 轮后有多少个亮着的灯泡。
解题方法
- 这一题的意思其实是 [1,n] 盏灯,然后 1x, 2x, 3x, 4x, …, n (2x表示 2 的倍数),所有的都要变换一下
- 拿 12 来举例,12 是 1x, 2x, 3x, 4x, 6x, 12x 也就是:开,关、开、关、开、关
- 再拿 16 来举例:16 是 1x, 2x, 4x, 8x, 16x 也就是:开,关、开、关、开
- 通过上面的例子可以大概理解了,最后状态的开关就和数 n 的因数的个数有关系,如果个数是 2 的倍数,最后是关,否则为开
- 什么数字 n 的因数的个数是奇数呢?就是 k ^ 2 = n, 也就是平方数的因数个数是奇数,因为因数是成对出现的, i * j = n, 只有 i == j 的时候没有成对出现,也就是 k * k = n , n 为平方数
class Solution {
public int bulbSwitch(int n) {
if (n == 0) return 0;
int res = (int) Math.sqrt(n);
return res;
}
}
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:35.2 MB,击败了67.25% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)