LeetCode:Bulb Switcher - 燈泡開關

一、題目名稱java

Bulb Switcher(燈泡開關)函數

二、題目地址測試

https://leetcode.com/problems/bulb-switcher/code

三、題目內容leetcode

英文: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.get

中文:現有n個燈泡,默認都是關閉的。第一輪會打開全部的燈泡,第二輪關閉全部偶數次序的燈泡,第三輪翻轉全部次序爲三的倍數位置的燈泡,直到第n輪撥動最後一個燈泡的開關。試肯定第n輪後還有幾盞燈是亮的。it

四、解題方法1(TLE)io

一開始我仍是嘗試着寫了一段用於暴力破解問題的代碼,這段代碼毫無懸念地會致使TLE(Time Limit Exceeded)。ast

Java代碼以下:class

/**
 * 燈泡開關測試
 * @文件名稱 Solution.java
 * @文件做者 Tsybius2014
 * @建立時間 2016年1月7日 下午11:11:02
 */
public class Solution {
    public int bulbSwitch(int n) {
        if (n <= 0) {
            return 0;
        }
        boolean[] bulbs = new boolean[n];
        for (int i = 0; i < n; i++) {
            bulbs[i] = false;
        }
        for (int i = 0; i <= n / 2; i++) {
            for (int j = i; j < n; j = j + i + 1) {
                bulbs[j] = !bulbs[j];
            }
        }
        for (int i = n / 2 + 1; i < n; i++) {
            bulbs[i] = !bulbs[i];
        }
        int counter = 0;
        for (boolean bulb : bulbs) {
            if (bulb) {
                counter++;
            }
        }
        return counter;
    }
}

五、解題方法2

後來我發現有一種方法更爲簡單,返回值其實就是n開方後向下取整的得數。

下面我來解釋一下。對於每一個數字來講,除了平方數,都有偶數個因數。

如6有4個因數:1×6=6,2×3=6

如60有個因數:1×60=60,2×30=60,3×20=60,4×15=60,5×12=60,6×10=60

能夠看出,非平方數的因數老是成對出現的,只有平方數的因數纔是奇數,由於平方數除平方根外,其餘的因數都是成對出現的!對於當前的開關燈泡問題,可知到最後處在平方數位置的燈泡必定是開啓的,其餘位置的燈泡必定是關閉的。而要計算一個數之下有多少小於或等於它的平方數,使用一個開平方用的函數就能夠了。

解題Java代碼以下:

/**
 * 燈泡開關測試
 * @文件名稱 Solution.java
 * @文件做者 Tsybius2014
 * @建立時間 2016年1月7日 下午11:11:02
 */
public class Solution {
    public int bulbSwitch(int n) {
        return (int) (n >= 0 ? Math.sqrt(n) : 0);
    }
}

END

相關文章
相關標籤/搜索