LeetCode Bulb Switcher 319,leetcodeswitcher

來源:互聯網
上載者:User

LeetCode Bulb Switcher 319,leetcodeswitcher

變換燈泡顏色

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

按題意coding

public int bulbSwitch(int n){        int[] arrN = new int[n];        int count = 0;        for (int i = 0; i < arrN.length; i++) {            arrN[i] =0;        }        for (int i = 0; i < arrN.length; i++) {            for (int j = 0; j < arrN.length;j++ ) {                if(i==0){                    arrN[j] = 1;//                    j++;                }else{                    int k = i+1;                    if((j+1)%k==0){arrN[j]=(arrN[j]==1?0:1);}//                    j=j+i;                }            }        }                for (int i = 0; i < arrN.length; i++) {            if (arrN[i]==1) {                count++;            }        }        return count;    }

 

運行逾時:

燈泡顏色的變換隻存在於自己的因子處

1.素數,只有1和自己。

2.普通數,因子成對出現。

3.只有完全平方數燈泡奇數次點亮不會熄滅。

此題轉化為求完全平方數的個數!!!

比如:3-->1,4-->2,10-->3

1 public static int bulbSwitch(int n){2     return (int)Math.sqrt(n);3 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.