Ugly Number II

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.


class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> buf2;
        vector<int> buf3;
        vector<int> buf5;
        buf2.push_back(1);
        buf3.push_back(1);
        buf5.push_back(1);
        int i = 0;
        int j = 0;
        int k = 0;
        int result = 0;
        while (n > 0)
        {
            result = min(min(buf2[i], buf3[j]), buf5[k]);
            buf2.push_back(result*2);
            buf3.push_back(result*3);
            buf5.push_back(result*5);
            if (buf2[i] == result)
            {
                i++;
            }
            if (buf3[j] == result)
            {
                j++;
            }
            if (buf5[k] == result)
            {
                k++;
            }

            n--;
        }

        return result;
    }
};


你可能感兴趣的:(Ugly Number II)