Java-NewCode-醜數

醜數
題目描述:

把只包含質因子2、3和5的數稱作醜數(Ugly Number)。例如6、8都是醜數,但14不是,因爲它包含質因子7。 習慣上我們把1當做是第一個醜數。求按從小到大的順序的第N個醜數。


public class Solution {
    public int GetUglyNumber_Solution(int index) {
        if(index<=0)
            return 0;
        int [] uglys = new int[index];
        uglys[0] = 1;
        int count = 1;
        int p2 = 0;
        int p3 = 0;
        int p5 = 0;
        int min = 0;
        while (count < index) {
            min = Min(uglys[p2] * 2, uglys[p3] * 3, uglys[p5] * 5);
            uglys[count] = min;
            while (uglys[p2]*2 <= min)
                p2++;
            while (uglys[p3]*3 <= min)
                p3++;
            while (uglys[p5]*5 <= min)
                p5++;
            count++;
        }
        return uglys[index-1];
    }
        private int Min(int a, int b, int c){
        return  a < b ? (a < c ? a : c ) : ( b < c ? b : c );
        }
}

喜歡折騰代碼的加羣(羣號:822286811)一起交流學習【Java、python、VBA、Shell、Linux、dos、數據分析、拆機、裝系統技術交流羣】
點擊鏈接加入羣聊【計算機技術交流

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章