/*题目:把只包含因子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;
}
面试题34:丑数
最新推荐文章于 2021-05-20 12:19:21 发布