问题描述:
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.有n盏电灯,序号设为1,2,3,...,n,初始状态都是关闭。现在对它们进行n次操作,第i次操作的对象是序号为i,2i,3i,...的电灯,每次操作改变其状态(关闭变成打开,打开变成关闭)。求最终有多少盏电灯打开。
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.
解法:
如果使用两层循环,提交结果是Time Limit exceeded。考虑到该问题实际上是求对于每个i(1≤i≤n),i能被多少个数整除,记为x(比如i=8,则1,2,4,8符合,8能被4个数整除),若x为偶数,该盏灯还是关闭的;反之亦然。现在再来看,一个数i,若有一个因子,必然能找到另一个因子为 i除以第一个因子的结果。只有某数是某数的平方,才为奇数。所以问题简单地归结为求sqrt(n)。
public class Solution {
public static int bulbSwitch(int n) {
double res = Math.sqrt(n);
return (int)res;
}
}