博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

程序员面试100题之三十七,寻找丑数

Posted on 2010-09-24 19:15  KurtWang  阅读(259)  评论(0编辑  收藏  举报
// 100_37.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

long ugly(long index)
{
	long * uglyNum = new long[index];
	uglyNum[0] = 1;
	long next = 1;
	long * p2 = uglyNum;
	long * p3 = uglyNum;
	long * p5 = uglyNum;

	while(next < index)
	{
		long temp2 = (*p2)*2;
		long temp3 = (*p3)*3;
		long temp5 = (*p5)*5;
		long min = temp2;
		if(temp3<temp2 && temp3<temp5)
			min = temp3;
		else if(temp5<temp3 && temp5<temp2)
			min = temp5;
		uglyNum[next] = min;
		while(*p2 * 2 <= min)
			++p2;
		while(*p3 * 3 <= min)
			++p3;
		while(*p5 * 5 <= min)
			++p5;
		next++;
	}
	long result = uglyNum[index-1];


	delete [] uglyNum;
	return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
	printf("%ld\n",ugly(100));
	return 0;
}