题目
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个灯拨一次开关;
第n轮每n个灯拨一次开关;
问最后还有几个灯是亮的?
分析
则不难发现第i轮开关灯涉及的开关号主要包括i*k个,k为整数;
同时,开关拨动次数为偶数时,灯泡灭;开关拨动次数为奇数时,灯泡亮;
灯牌是否亮判断的方式为该灯泡开关拨动的次数是否为奇数;
因此第n个灯泡最后是否亮取决于灯泡号的因数是否为奇数个。
对于第i个灯泡,当i的因子个数为奇数时,最终会保持点亮状态,例如9的因子为1,3,9而当i的因子个数为偶数时,最终会保持熄灭状态,例如8的因子为:1,2,4,8当且仅当i为完全平方数时,其因子个数为奇数。
为什么只有完全平方数的因子个数为奇数?因为除了完全平方数,其余数字的因子都是成对出现的,而完全平方数的平方根只会统计一次。
对n开平方并取整即可得到结果
源码
class Solution {
public:
int bulbSwitch(int n) {
int result = 0;
for (int i = 1; i*i<=n;++i) {
++result;
}
return result;
}
};
优化的结果:
class Solution {
public:
int bulbSwitch(int n) {
return (sqrt(n));
}
};
JavaScript:
/**
* @param {number} n
* @return {number}
*/
var bulbSwitch = function(n) {
var result=Math.sqrt(n);
return parseInt(result);
};