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 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.
解法一:
代码:
public class Solution {
public int bulbSwitch(int n) {
int count = 0;
int result = 0;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
if(i % j == 0){
count++;
}
}
if(count % 2 == 1){
result++;
}
}
return n >= 0 ? result : 0;
}
}
此方法过于复杂,提交时会抛出异常 Time Limit Exceeded
解法二:一般来说,约数都是成对出现的。约数是奇数的情况只有在平方数才出现。那么代码可以改进为
代码:
public class Solution {
public int bulbSwitch(int n) {
int result = 0;
for(int i = 1; i * i <= n; i++){
result++;
}
return (n >= 0 ? result : 0);
}
}
上述代码有改进的空间,小于 n 的平方数的个数可以直接计算 n 的平方根得到:
代码:
public class Solution {
public int bulbSwitch(int n) {
return (int)(n >= 0 ? Math.sqrt(n) : 0);
}
}