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
对于每个数字来说,进行因子分解如下
如6有4个因数:1×6=6,2×3=6,而这4个因子处都要经过偶数次变换,则灯仍是熄灭状态。
除了平方数,都有偶数个因数,非平方数的因数总是成对出现的,而对于平方数的因数,只有一次变换机会,因此,灯的状态在平方数的因数处只变换一次,即灯处于亮着的状态,对于当前的开关灯泡问题,可知到最后处在平方数位置的灯泡一定是开启的,其他位置的灯泡一定是关闭的。而要计算一个数之下有多少小于或等于它的平方数,使用一个开平方用的函数就可以了。
public class Solution {
public int bulbSwitch(int n) {
// int count=1;//记录亮的灯泡数
// if(n==0)
// {
// return 0;
// }else if(n==1)
// {
// return 1;
// }else
// {
// for(int i=2;i<=n;i++)
// {
// int k=0;//求n对于i的倍数
// if((Math.floor(n/i))%2==0)//若为偶数被,灯泡将亮
// {
// count++;
// }
// }
// }
// return count;
return n>0?(int)Math.floor(Math.sqrt(n)):0;
}
}