Leetcode 319. Bulb Switcher

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.

Next challenges: Reverse Integer Smallest Good BaseFind the Derangement of An Array

思路:首先说明一下示例。

第1轮,每1个取反,就是每个为单位的最后1个取反;第2轮,每2个取反,就是每2个为单位的最后1个取反;第3轮,每3个取反,就是每3个为单位的最后1个取反。

注意到对于特定i位置的灯,i有几个因数就被改变几次,对应的,只要i有奇数个因数,i最后一定是on状态。实际上,除了平方数,一般的整数的因数都是成对出现的,因此本题只要找到不大于n的平方数的数据即可。

代码:

1 public class Solution {
2     public int bulbSwitch(int n) {
3         return (int)Math.sqrt(1.0*n);
4     }
5 }
原文地址:https://www.cnblogs.com/Deribs4/p/7205382.html