319. Bulb Switcher

1、来源:点击打开链接

2、

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. Find how many bulbs are on after n rounds.

Example:

Given n = 3. 
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.
3、暴力破解又超时,心里苦(java):

public class Solution {
    public int bulbSwitch(int n) {
        int[] count=new int[n];
        int i,j,sum=0;
        for(i=0;i<n;i++)
            count[i]=0;
        for(i=0;i<n;i++){
            j=i;
            while(j<n){
                count[j]=count[j]==0?1:0;
                j+=(i+1);
            }
        }
        for(i=0;i<n;i++)
            sum+=count[i];
        return sum;
    }
}
4、列出很多例子,可以发现规律(c++),虽然不是从“on,off的切换得出”,也不知道为什么,但出产自己还是很爽的:

class Solution {
public:
    int bulbSwitch(int n) {
        return sqrt(n);
    }
};
5、在discuss区中有解释https://discuss.leetcode.com/topic/31929/math-solution/34:

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

Call them bulb 1 to bulb n. Bulb i is switched in round d if and only if d divides i. So bulb i ends up on if and only if 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 when 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 if and only if i is a square.

表达的意思是:如果一盏灯最终是亮的话,则它被点击的次数为奇;

例如当n=10时,我们分别计算一些灯的on,off情况,

第1盏亮

第2盏不亮:2=2*1,意为把2分解2和1,,只有第1,2次要转换;

第3盏不亮:3=3*1,意为把3分解3和1,,只有第1,3次要转换;

第5盏不亮:5=5*1,意为把5分解3和1,,只有第1,5次要转换;

第6盏不亮:6=6*1或6=3*2,只有第1,2,3,6次要转换;

。。。。。。

从上面可以看出来,如果不是完全平方数分解,必定都是偶数次转换。而如9=9*1或9=3*3,则是偶数次转换;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值