您的位置:首页 > 编程语言 > Java开发

(java)Bulb Switcher

2016-05-16 16:34 447 查看
题意:(开灯关灯的问题,轮训)

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)最后整理的思路:先N以内所有数的因子有多少个,如果是奇数个就count++;

public static int bulbSwitch(int n) {
int[] temp=new int[n+1];
for(int i=1;i<=n;i++){
for(int j=2;i*j<=n;j++){
temp[i*j]++;
}
}
int count=0;
for(int i=1;i<=n;i++){
if(temp[i]%2==0){
count++;
}
}
return count;
}

  (2)超时,进而思路:N以内只有是能开方的数的因子才是奇数个,所以求N以内能开方(完全平方数比如4,9,16......)的数的个数就行

public class Solution {
public int bulbSwitch(int n) {
int count=0;
for(int i=1;i<=n;i++){
if(i==(int)Math.sqrt(i)*(int)Math.sqrt(i)){
count++;
}
}
return count;
}
}

(3)超时,进而思路,,直接求个数(网上更简洁的方式是return Math.sqrt(N))

public class Solution {
public int bulbSwitch(int n) {
int count=0;
for(int i=1;i*i<=n;i++){
count++;
}
return count;
}
}

   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 编程