2016年2月4日 星期四

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



笨蛋法
用一個陣列去記你現在的倍數
但是太慢了
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
int bulbSwitch(int n) {
    if(n==0)return 0;
    int *tag=(int *)malloc(sizeof(int)*n);
    memset(tag,1,sizeof(int)*n);
    int ans=1;
    for(int i=1;i<n;i++){
        for(int j=i;j<n;j+=(i+1)){
            tag[j]++;
        }
        if(tag[i]%2!=0)ans++;
    }
    return ans;
}

-------------------

我想說換一個判斷是不是質數來算
但是還是太慢

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
int bulbSwitch(int n) {
    if(n==0)return 0;
    if(n==1)return 1;
    int *prims = (int*)malloc(sizeof(int)*n);
    int Size=0,ans=1;
    for(int i=2;i<=n;i++){
        int total = Isprime(prims,&Size,i);
        if(total%2==0)ans++;
    }
    return ans;
    
}

int Isprime(int *prims,int *primeSize,int target){
    int temp =target;
    int accum=0,total=1;
    for(int i=0;i<*primeSize;i++){
        if(prims[i] > target || temp==0)break;
        while(temp%prims[i]==0){
            //printf("(W %d %d)",temp,prims[i]);
            temp/=prims[i];
            accum++;
        }
        total*=(accum+1);
    }
    if(total<=1){
        prims[*primeSize]=target;
        *primeSize+=1;
        //printf("(P %d )",target);
        return 1;
    }else{
        return total-1;
    }
    if(total==1){
        prims[*primeSize]=target;
        *primeSize++;
    }
    return total; 
}
-------------------
最簡單方法
開平方
1 --------- 1



2 --------- 1, 2



3 --------- 1, 3



4 --------- 1, 2, 4



5 --------- 1, 5



6 --------- 1, 2, 3, 6



7 --------- 1, 7



8 --------- 1, 2, 4, 8



9 --------- 1, 3, 9



所以找平方數字有多少個就好


1
2
3
4
5
6
7
int bulbSwitch(int n) {
    int count=0;
    for(int i =1;i*i<=n;i++){
        count++;
    }
    return count;
}

沒有留言:

張貼留言