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个灯泡,初始状态是关闭的。第一轮,打开所有灯泡,第二轮关掉所有2的倍数的灯泡,第三轮转换所有3的倍数的灯泡开关状态,以此类推,知道第n轮,转换所有n的倍数的灯泡开关,找出有几盏灯泡是开着的
算法分析
灯泡开始是关闭状态。奇数次轮以后,为开启状态;偶数次轮后为关闭状态。因此本题也就是转化为寻找小于等于n的数的因数的个数为奇数的情况。只有平方数的因数为奇数个
例如:6的因数为1,6,2,3;而9的因数为1,9,3;
Java代码
public class Solution {
public int bulbSwitch(int n) {
if(n <= 0) return 0;
return (int)Math.sqrt(n);//本题最后转化为求小于等于n的平方数的个数
}
}