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.
s思路: 1. 老題了,畫(huà)一下,就發(fā)現(xiàn)是個(gè)數(shù)學(xué)題。例如:6號(hào)這個(gè)燈泡,在第1次,第6次一開(kāi)一關(guān),在第2次,第3次一開(kāi)一關(guān),最后就回到了初始狀態(tài),用數(shù)學(xué)語(yǔ)言來(lái)說(shuō):6=1*6, 6還可以等于2*3,因此成對(duì)的操作就相互抵消了;那最后怎么還有燈泡是打開(kāi)的呢?比如:4=1*4,4還可以等于2*2,看見(jiàn)沒(méi),4因?yàn)槭峭耆椒剑栽?的時(shí)候只能操作一次而不能抵消,因此最后打開(kāi)的燈泡都是完全平方數(shù)的位置。 2. 起始看到隔多少個(gè)燈泡操作一次,這個(gè)隔,也就表示了乘法的意思!
//方法1:老實(shí)版本class Solution {public: int bulbSwitch(int n) { int count=0; for(int i=1;i*i<=n;i++){ count++; } return count; }};//方法2:有點(diǎn)沒(méi)想到,還可以這么猥瑣class Solution {public: int bulbSwitch(int n) { return sqrt(n); }};新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注