[LeetCode] (medium) 319. Bulb Switcher

5 篇文章 0 订阅
5 篇文章 0 订阅

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

 https://blog.csdn.net/zhangxiao93/article/details/50370170

标准答案
One line XXX solution,这是Discuss区域的答案,原来是一道数学题,虽然感觉自己的智商确实被碾压,但是感觉其实很多解并没有说出详细原因,直到看到https://leetcode.com/discuss/75014/math-solution,给出的解释非常清楚:

A bulb ends up on iff it is switched an odd number of times.

Bulb i is switched in round d iff d divides i. So bulb i ends up on iff it has an odd number of >divisors.

Divisors come in pairs, like i=12 has divisors 1 and 12, 2 and 6, and 3 and 4. Except if i is a >square, like 36 has divisors 1 and 36, 2 and 18, 3 and 12, 4 and 9, and double divisor 6. So bulb >i ends up on iff and only if i is a square.

So just count the square numbers.

大概解释一下,当一个灯泡被执行偶数次switch操作时它是关着的,当被执行奇数次switch操作时它是开着的,那么这题就是要找出哪些编号的灯泡会被执行奇数次操作。

现在假如我们执行第ii次操作,即从编号i开始对编号每次+i+i进行switch操作,对于这些灯来说, 
如果其编号j(j=1,2,3,⋯,n)j(j=1,2,3,⋯,n)能够整除i,则编号jj的灯需要执switch操作。 
具备这样性质的ii是成对出现的,比如: 
j=12j=12时,编号为12的灯,在第1次,第12次;第2次,第6次;第3次,第4次一定会被执行Switch操作,这样的话,编号为12的等肯定为灭。 
但是当完全平方数36就不一样了,因为他有一个特殊的因数6,这样当i=6i=6时,只能被执行一次Switch操作,这样推出,完全平方数一定是亮着的,所以本题的关键在于找完全平方数的个数。 
代码:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值