319. Bulb Switcher

来源:互联网 发布:java const类 注意点 编辑:程序博客网 时间:2024/06/10 00:47

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的因子,灯泡状态才能改变。例如对第18个灯泡,(1,18)(2,9)(3,6)。第1轮点亮,第18轮正好对应把灯关了,第2轮点亮,第9轮对应关了,第3轮点亮,第6轮又关了。
但是对于第25个灯泡,(1,25)(5,5)。第5轮点亮后,状态就不改变了,第1个灯泡(1,1),第4个灯泡(1,4)(2,2),第9个灯泡(1,9)(3,3),所以在n内的平方数的位置的灯泡最后是亮着的

class Solution {public:    int bulbSwitch(int n) {        return sqrt(n);    }};
0 0
原创粉丝点击