319. Bulb Switcher

来源:互联网 发布:java 网络服务器 编辑:程序博客网 时间:2024/06/05 14:53

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 theith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.Find how many bulbs are on aftern 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.

Subscribe to see which companies asked this question

分析:

对于某一个灯来说,会被能整除自己数按掉,而一个数的因数是成对出现的,比如12: 1,12,2,6,3,4。除了那些可以开方的数,比如36,1,36,2,18,3,12,4,9,6.因此每一个灯都会被按偶数次,最后都会灭,只有奇数个因子的灯才会亮,换句话说,只有平方数才会最后是亮的。

代码:

class Solution {public:    int bulbSwitch(int n) {        if(n==0) return 0;        if(n==1) return 1;        int temp=0;        int count=0;        for(int t=1;t<((n)/2+1);++t)        {            temp=t*t;            if(temp<0) break;            if(temp<=(n)) {++count;}        }        return count;    }};


0 0
原创粉丝点击