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.
有n个灯泡,初始全部关闭,第1次全部打开,第2次隔一个关闭,第3次每3个切换一个灯的状态(若原来打开则关闭,若原来关闭则打开)。。。第n次时仅切换第n个灯。求经过n轮,最终有多少个灯处于打开状态。
分析:
对于第i个灯泡,每当处于它的因数轮时,将切换状态。因初始为关闭,若经过奇数次切换,则最终为打开状态;若经过偶数次切换,则最终为关闭状态。原题变为求1~n之间经过奇数次切换的数的个数。观察前几项的状态切换:
第1个:1*1 off->on
第2个:1*2 2*1 off->on->off
第3个:1*3 3*1 off->on->off
第4个:1*4 2*2 4*1 off->on->off->on
第5个:1*5 5*1 off->on->off
第6个:1*6 2*3 3*2 6*1 off->on->off->on->off
第7个:1*7 7*1 off->on->off
第8个:1*8 2*4 4*2 8*1 off->on->off->on->off
第9个:1*9 3*3 9*1 off->on->off->on
...
可发现仅当i为完全平方数时才经过奇数次切换,否则必为偶数次切换。由此,原题为求1~n之间的完全平方数的个数。
代码如下:
int bulbSwitch(int n)
{
int result = 0;
for (int i = 1; i*i <= n; i++)
result++;
return result;
}
搜索了其他网友的解法后,发现还有更简便的解法。
代码如下:
int bulbSwitch(int n)
{
return (int)sqrt(n);
}
仔细一想,确实是这样,因为sqrt(n)*sqrt(n)<=n,1~sqrt(n)之间的整数(不含n)的平方当然小于n。因此1~n之间的完全平方数的个数即为sqrt(n)。
浙公网安备 33010602011771号