面试题43:丑数

方法一:逐个数进行判断是否为丑数,效率低下

代码如下:

#include "stdafx.h"
#include <iostream>
using namespace std;

//判断一个数是否为丑数  1被认为是第一个丑数
bool IsUglyNum(int nNum)
{
	if (nNum <= 0)
	{
		return false;
	}

	while (nNum % 2 == 0)
	{
		nNum /= 2;
	}

	while (nNum % 3 == 0)
	{
		nNum /= 3;
	}

	while (nNum % 5 == 0)
	{
		nNum /= 5;
	}

	return (nNum == 1) ? true : false;
}

//返回第nIndex个丑数
int GetUglyNum(int nIndex)
{
	if (nIndex <= 0)
	{
		return 0;
	}

	int nNum = 1;
	int nUglyNum = 0;//记录第nIndex个丑数
	int nCount = 0;//计数

	while (nCount < nIndex)
	{		
		if (IsUglyNum(nNum))
		{
			nCount++;			
		}

		nNum++;
	}

	nUglyNum = nNum - 1;
	return nUglyNum;
}

int _tmain(int argc, _TCHAR* argv[])
{
	cout << GetUglyNum(7) << endl;
	system("pause");
	return 0;
}


方法二:空间换时间,用一个数组保存排好序的丑数

代码如下:

#include "stdafx.h"
#include <iostream>
using namespace std;

int Min(int a, int b, int c)
{
	int nMin = (a > b) ? b : a;
	return (nMin > c) ? c : nMin;
}

//返回第nIndex个丑数
int GetUglyNum(int nIndex)
{
    if (nIndex <= 0)
    {
		return 0;
    }

	//申请一个数组空间存放丑数
	int *pUglyNum = new int[nIndex];
	pUglyNum[0] = 1;

	int *pUglyNum2 = pUglyNum;
	int *pUglyNum3 = pUglyNum;
	int *pUglyNum5 = pUglyNum;
	int nNextIndex = 1;
	int nMin = 0;

	while (nNextIndex < nIndex)
	{
        nMin = Min((*pUglyNum2) * 2, (*pUglyNum3) * 3, (*pUglyNum5) * 5);
		pUglyNum[nNextIndex] = nMin;

		while ((*pUglyNum2) * 2 <= pUglyNum[nNextIndex])
		{
			++pUglyNum2;
		}

		while ((*pUglyNum3) * 3 <= pUglyNum[nNextIndex])
		{
			++pUglyNum3;
		}

		while ((*pUglyNum5) * 5 <= pUglyNum[nNextIndex])
		{
			++pUglyNum5;
		}

		nNextIndex++;
	}

	int nUglyNum = pUglyNum[nIndex - 1];
	delete [] pUglyNum;
	return nUglyNum;
}

int _tmain(int argc, _TCHAR* argv[])
{
	cout << GetUglyNum(1500) << endl;
	system("pause");
	return 0;
}


 

你可能感兴趣的:(面试题43:丑数)