1 暴力解法(超时):
package leetcode;
public class Solution319 {
public int bulbSwitch(int n) {
if(n == 0){
return 0;
}
boolean[] bulbs = new boolean[n];
int count = 1;
int numOfbulbs = 0;
while(count <= n) {
for(int i = count-1; i < n; i+=count) {
if(bulbs[i]) {
bulbs[i] = false;
}else{
bulbs[i] = true;
}
}
++count;
}
StringBuffer s = new StringBuffer(new String(""));
for(int i = 0;i < n; ++i){
if(bulbs[i]){
++ numOfbulbs;
}
s.append(bulbs[i] ? 1 : 0);
}
System.out.println(s);
return numOfbulbs;
}
public static void main(String[] args) {
Solution319 solution319 = new Solution319();
int n = 30;
for(int l = 0;l < 30; ++l) {
solution319.bulbSwitch(l);
}
}
}
2 找规律解法:
打印输出出规律,然后再看具体的情况。
code:
public class Solution319Lcq {
public int bulbSwitch(int n) {
if(n <= 3){
return 1;
}
int wheel = 2;
int result = 0;
int trackvehicle = 0;
boolean isNotWheel = true;
while(trackvehicle <= n){
if(isNotWheel) {
trackvehicle += 1;
result += 1;
//wheel;
isNotWheel = !isNotWheel;
}else{
trackvehicle += wheel;
wheel += 2;
isNotWheel = !isNotWheel;
}
}
return result;
}
}