面试题34:丑数

/*题目:把只包含因子2、3和5的数称作丑数,求按从小到大的顺序的第1500个丑数。例如6、8都是丑数,但14不是
,因为它包含7.习惯上我们把1当做第一个丑数。*/
#include <iostream>
using namespace std;
//得到三个数中的最小数
int Min(int number1, int number2, int number3)
{
    int min = (number1 < number2) ? number1 : number2;
    min = (min < number3) ? min : number3;
    return min;
}
//将所得丑数从小到大排列到一个数组中(利用空间换时间)
int GetUglynumber(int index)
{
    if(index <= 0)
    return 0;
    int *pGetUglynumbers = new int [index];
    //相关初始化
    pGetUglynumbers[0] = 1;
    int pNextUglyIndex = 1;

    int *pMultiply2 = pGetUglynumbers;
    int *pMultiply3 = pGetUglynumbers;
    int *pMultiply5 = pGetUglynumbers;
    //循环判断直至找到想要的丑数
    while(pNextUglyIndex < index)
    {
        int min = Min((*pMultiply2) * 2, (*pMultiply3) * 3, (*pMultiply5) * 5);
        //存储下一个丑数
        pGetUglynumbers[pNextUglyIndex] = min;
        while((*pMultiply2) * 2 <= pGetUglynumbers[pNextUglyIndex])
        ++pMultiply2;

        while((*pMultiply3) * 3 <= pGetUglynumbers[pNextUglyIndex])
        ++pMultiply3;

        while((*pMultiply5) * 5 <= pGetUglynumbers[pNextUglyIndex])
        ++pMultiply5;

        ++pNextUglyIndex;
    }
    int ugly = pGetUglynumbers[pNextUglyIndex - 1];
    delete [] pGetUglynumbers;
    return ugly;
}
//=================第二种方法===================
bool IsUglyNumber(int number)
{
    while(number % 2 == 0)
    number /= 2;

    while(number % 3 == 0)
    number /= 3;

    while(number % 5 == 0)
    number /= 5;

    return (number == 1) ? true : false;
}
//由于需要计算每一个数所以时间效率不高
int GetUglynumber2(int index)
{
    if(index <= 0)
    return 0;
    int Uglycount = 0;
    int number = 0;
    while(Uglycount < index)
    {
        number++;
        if(IsUglyNumber(number))
        {
            Uglycount++;
        }
    }
    return number;
}
//================测试代码======================
void Test(int index, int expected)
{
    if(GetUglynumber(index) == expected)
    cout << "Passed!" << endl;
    else
    cout << "Failed!" << endl;
    //第二种方法
    if(GetUglynumber2(index) == expected)
    cout << "2Passed!" << endl;
    else
    cout << "2Failed!" << endl;
}
int main()
{
    Test(1, 1);
    Test(2, 2);
    Test(3, 3);
    Test(4, 4);
    Test(5, 5);
    Test(6, 6);
    Test(7, 8);
    Test(8, 9);
    Test(9, 10);
    Test(10, 12);
    Test(11, 15);

    Test(1500, 859963392);

    Test(0, 0);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值