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.spa

Example:code

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。blog

4=2x2是徹底平方數。
5不是徹底平方數。three

對於第4個燈, 4=1x4=2x2。
n=1時,它被打開。
n=2時,它被關閉。
n=4時,它被打開。
徹底平方數保證了他被操做奇數次。it

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

 

class Solution {
public:
  int bulbSwitch(int n) {
   return sqrt(n);
}
};
相關文章
相關標籤/搜索