【LeetCode】319. Bulb Switcher 灯泡开关(Medium)(JAVA)

【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:

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. 这一题的意思其实是 [1,n] 盏灯,然后 1x, 2x, 3x, 4x, …, n (2x表示 2 的倍数),所有的都要变换一下
  2. 拿 12 来举例,12 是 1x, 2x, 3x, 4x, 6x, 12x 也就是:开,关、开、关、开、关
  3. 再拿 16 来举例:16 是 1x, 2x, 4x, 8x, 16x 也就是:开,关、开、关、开
  4. 通过上面的例子可以大概理解了,最后状态的开关就和数 n 的因数的个数有关系,如果个数是 2 的倍数,最后是关,否则为开
  5. 什么数字 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用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值