你的位置:首页 > Java教程

[Java教程]319. Bulb Switche


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.
代码如下:(超时,但运行结果正确)

 1 public class Solution { 2   public int bulbSwitch(int n) { 3     if(n==0) 4     return 0; 5     if(n==1) 6     return 1; 7      8     int[] a=new int[n]; 9     for(int i=0;i<n;i++)10     a[i]=1;11     for(int j=2;j<=n;j++)12     {13       int k=1;14       while(j*k-1<=n-1)15       {16         if(a[j*k-1]==0)17         a[j*k-1]=1;18         else19         a[j*k-1]=0;20         k++;21       }22     }23     int count=0;24     for(int j=0;j<n;j++)25     {26       if(a[j]==1)27       count++;28     }29     return count;30   }31 }