1. 程式人生 > >319 bulb switcher

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 i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n

 rounds.

Example:

Input: 3
Output: 1 
Explanation: 
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.

 

解法
求1-n中完全平方數的個數。
舉例,假設n=5。

4=2x2是完全平方數。
5不是完全平方數。

對於第4個燈, 4=1x4=2x2。
n=1時,它被開啟。
n=2時,它被關閉。
n=4時,它被開啟。
完全平方數保證了他被操作奇數次。

對於第5個燈,5=1x5
n=1時,它被開啟。
n=5時,它被關閉。

 

class Solution {
public:
  int bulbSwitch(int n) {
   return sqrt(n);
}
};