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.
Return the number of bulbs that are on after n rounds.
319. 灯泡开关 - 力扣(LeetCode) (leetcode-cn.com)
【题解】
由题意可知,当进行了n轮之后还是亮着的灯一定是被按了奇数次,那个灯被按的次数是他的编号的约数个数
比如:
4
那在1,2,4都会被按到
我们也可以发现,对于n的约数,都是成对出现的
比如:
1和4, 2和2(所以这是奇数个数的约数)都是4的约数
【数学魔法?】
要想知道n以内有多少盏灯还亮着,就只要看看n以内有多少数可以开方
1 2 3 4 5 6 7 8 9 10
一共有三个数可以开方,就是1,4,9
其实也就是根号10个数可以开方
【1,2,3的平方都在10内,而4的平方16在10外了,所以只有三个,也就是根号10个】
所以这道题直接:
class Solution {
public int bulbSwitch(int n) {
return (int)Math.sqrt(n);
}
}