1. 程式人生 > >劍指offer____醜數

劍指offer____醜數

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

class Solution {
public:
    
    bool IsUgly(int num)
    {
        while(num % 2 == 0) num /= 2;
        while(num % 3 == 0) num /= 3;
        while(num % 5 == 0) num /= 5;
        return (num == 1) ? true:false;
    }
    int GetUglyNumber_Solution(int index) 
    {
        if(index <= 0) return -1;
       // if(index == 1) return 1;
        int count = 0;
        int number = 0; 
        while(count < index)
        {
             number++;
            if(IsUgly(number))
            {
                count++;
            }
        }
        return number;
    }
 };   

方法二:

class Solution {
public:
    int Min(int num1,int num2,int num3)
    {
        int min = num1 < num2 ? num1:num2;
        min = min < num3 ? min:num3;
        return min;
    }
    int GetUglyNumber_Solution(int index) 
    {
        if(index <= 0) return 0;
        int *p = new int [index];
        p[0] = 1;
        int nextInd = 1;
        int *p2 = p;
        int *p3 = p;
        int *p5 = p;
        while(nextInd < index)
        {
            int min = Min(*p2 *2,*p3 *3,*p5*5);
            p[nextInd] = min;
            while(*p2 * 2 <= p[nextInd])  p2++;
            while(*p3 * 3 <= p[nextInd])  p3++;
            while(*p5 * 5 <= p[nextInd])  p5++;
            ++nextInd;
        }
        int ugly = p[nextInd - 1];
        delete []p;
        return ugly;
    }
};