您的位置:首页 > 其它

LeetCode 319 Bulb Switcher

2016-05-02 17:53 232 查看
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个灯泡,默认都是关闭的。第一轮会打开所有的灯泡,第二轮关闭所有偶数次序的灯泡,第三轮翻转所有次序为三的倍数位置的灯泡,直到第n轮拨动最后一个灯泡的开关。试确定第n轮后还有几盏灯是亮的。

思路和解法:

1.标号为k的灯,它是on或者off,取决于它的因子个数是奇数还是偶数;如果k的因子总数为奇数个,那么最后它是on的,如果是偶数,那么最后是off的。

2.如果k的因子总数是奇数个,那么k一定是某个数的平方。因为因子一般都是成对出现的,被平方的那个数才可以单个出现。比如36=1*36=2*18=3*12=4*9=6*6,36的因子为1,2,3,4,6,9,12,18,36,其中1*36=2*18=3*12=4*9,都是成对出现的,6和6一样,因此只出现一次,所以最后36的因子总数为奇数。36是6的平方。

3.n个灯,这样操作n次,最后状态为on的灯,标号是1*1,2*2,3*3,4*4……k*k……m*m的灯,m*m<=n。状态on的灯总数为m个。m就是n的平方根的整数部分。

public int bulbSwitch(int n) {
return (int) Math.sqrt(n);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: