1. 程式人生 > >319. Bulb Switcher

319. Bulb Switcher

完全 use eve 簡化 開始 there cau 它的 當前

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.

題目含義:首先定義操作叫做switch:如果燈開著就關,如果關著就開。
第一次,從1開始以每次+1的方式叠代執行switch
第二次,從2開始以每次+2的方式叠代執行switch

第n次,對最後一個燈執行switch

 1     public int bulbSwitch(int n) {
 2 //        最後我們發現五次遍歷後,只有1號和4號鎖是亮的,而且很巧的是它們都是平方數,是巧合嗎,還是其中有什麽玄機。我們仔細想想,對於第n個燈泡,
 3 // 只有當次數是n的因子的之後,才能改變燈泡的狀態,即n能被當前次數整除,比如當n為36時,它的因數有(1,36), (2,18), (3,12), (4,9), (6,6),
 4 // 可以看到前四個括號裏成對出現的因數各不相同,括號中前面的數改變了燈泡狀態,後面的數又變回去了,等於鎖的狀態沒有發生變化,只有最後那個(6,6),
 5 // 在次數6的時候改變了一次狀態,沒有對應其它的狀態能將其變回去了,所以鎖就一直是打開狀態的。
6 // 所以所有平方數都有這麽一個相等的因數對,即所有平方數的燈泡都將會是打開的狀態。 7 // 那麽問題就簡化為了求1到n之間完全平方數的個數,我們可以用force brute來比較從1開始的完全平方數和n的大小 8 int res=1; 9 while (res*res<=n) res++; 10 return res-1; 11 }

319. Bulb Switcher