当前位置:网站首页>319. Bulb switch

319. Bulb switch

2022-07-05 08:35:00 Mr Gao

319. Bulb switch

Initially there is n One bulb is off . The first round , You'll turn on all the lights . The next round , You will turn off the second light bulb every two .

The third round , You switch the third bulb every three bulbs ( namely , Open to close , Turn off to turn on ). The first i round , Every time you i Switch the first light bulb i A light bulb switch . Until the first n round , You just need to switch the last light bulb .

Find out and return to n How many light bulbs are there behind the wheel .

Example 1:
 Insert picture description here

Input :n = 3
Output :1
explain :
At the beginning , Lamp status [ close , close , close ].
After the first round , Lamp status [ Turn on , Turn on , Turn on ].
After the second round , Lamp status [ Turn on , close , Turn on ].
After the third round , Lamp status [ Turn on , close , close ].

You should go back 1, Because only one bulb is still on .

Example 2:

Input :n = 0
Output :0

Example 3:

Input :n = 1
Output :1

Whether the light bulb is off here is related to his approximate number :
The conventional problem-solving code is as follows :

int f(int n){
    
    int count=1;
    int i;
    for(i=2;i<=n/2;i++){
    
        if(n%i==0){
    
            count++;
        }


    }
    return count;
}

int bulbSwitch(int n){
    

    int i;
    if(n==0){
    
        return 0;
    }
    int count=1;
    for(i=2;i<=n;i++){
    
        int c=f(i);
       // printf("%d ",c);
        if(c%2==0){
    
            count++;
        }

    }
    return count;

}

The following is also a very good skill solution :


int bulbSwitch(int n){
    

    int i;
    if(n==0){
    
        return 0;
    }
   int count=1;
   for(i=2;i<=n;i++){
    
       if(i*i>n){
    
           return i-1;

       }
   }
   
    return count;

}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050830330686.html