丑数

出自:何海涛的剑指offer

丑数_第1张图片


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

int min(int a, int b, int c)
{
	int temp = (a>b)?b:a;

	return (temp>c)?c:temp;
}

int GetUglyNumber(int index)
{
	if (index <=0 )
		return 0;
	int* pUglyNumbers = new int[index];
	pUglyNumbers[0] = 1;
	int nextUglyIndex = 1;

	int* pMultiply2 = pUglyNumbers;
	int* pMultiply3 = pUglyNumbers;
	int* pMultiply5 = pUglyNumbers;

	while ( nextUglyIndex < index )
	{  
		int MinUgly = min(*pMultiply2 *2, *pMultiply3 *3, *pMultiply5 *5);
		pUglyNumbers[nextUglyIndex] = MinUgly;

		while (*pMultiply2 *2 <= MinUgly )
			pMultiply2++;
		while (*pMultiply3 *3 <= MinUgly )
			pMultiply3++;
		while (*pMultiply5 *5 <= MinUgly )
			pMultiply5++;

		nextUglyIndex++;
	}
	int ugly = pUglyNumbers[nextUglyIndex-1];
	delete[] pUglyNumbers;

	return ugly;
}

int _tmain(int argc, _TCHAR* argv[])
{
	cout << GetUglyNumber(1500) <<endl;

	system("pause");
	return 0;
}


你可能感兴趣的:(丑数)