首页 > 其他 > 详细

319. Bulb Switche

时间:2016-04-26 14:01:57      阅读:244      评论:0      收藏:0      [点我收藏+]

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                 else
19                 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 }

 

319. Bulb Switche

原文:http://www.cnblogs.com/ghuosaao/p/5434715.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!