丑数

题目

把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

 

C++代码

class Solution {
public:
    int GetUglyNumber_Solution(int index) {
        if(index <= 0) return 0;
        vector<int> res(index);
        res[0] = 1;
        int p2 = 0, p3 = 0, p5 = 0;
        for(int i=1; i<index; i++)
        {
            int k = min(res[p2] * 2, res[p3] * 3);
            k = min(k, res[p5] * 5);
            if(k == res[p2] * 2)
                p2++;
            if(k == res[p3] * 3)
                p3++;
            if(k == res[p5] * 5)
                p5++;
            res[i] = k;
        }
        return res[index-1];
    }
};

 

posted @ 2019-08-10 16:26  xd_xumaomao  阅读(120)  评论(0编辑  收藏  举报