319. 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.

319. 灯泡开关 - 力扣(LeetCode) (leetcode-cn.com)

【题解】

由题意可知,当进行了n轮之后还是亮着的灯一定是被按了奇数次,那个灯被按的次数是他的编号的约数个数

比如:

4

那在1,2,4都会被按到

我们也可以发现,对于n的约数,都是成对出现的

比如:

1和4,  2和2(所以这是奇数个数的约数)都是4的约数

【数学魔法?】

要想知道n以内有多少盏灯还亮着,就只要看看n以内有多少数可以开方

1 2 3 4 5 6 7 8 9 10

一共有三个数可以开方,就是1,4,9

其实也就是根号10个数可以开方

【1,2,3的平方都在10内,而4的平方16在10外了,所以只有三个,也就是根号10个】

所以这道题直接:

class Solution {
    public int bulbSwitch(int n) {
        return (int)Math.sqrt(n);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值