码迷,mamicode.com
首页 > 其他好文 > 详细

34丑数

时间:2015-07-10 16:49:26      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:数组

技术分享

技术分享

bool IsUgly(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 GetUglyNumber(int index)
{
if (index <= 0)
return 0;
int number = 0;
int uglyFound = 0;
while (uglyFound < index)
{
++number;
if (IsUgly(number))
{
++uglyFound;
}
}
return number;
}

只需要在函数GetUglyNumber中传入参数1500,就能得到第1500个丑数。但是每个整数都需要做求余和除法运算,时间效率不是很高。

技术分享

技术分享

int GetUglyNumber_Solution2(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 min = Min(*pMultiply2 * 2, *pMultiply3 * 3, *pMultiply5 * 5);
pUglyNumbers[nextUglyIndex] = min;
while (*pMultiply2 * 2 <= pUglyNumbers[nextUglyIndex])
   ++pMultiply2;
while (*pMultiply3 * 3 <= pUglyNumbers[nextUglyIndex])
++pMultiply3;
while (*pMultiply5 * 5 <= pUglyNumbers[nextUglyIndex])
++pMultiply5;
++nextUglyIndex;
}
int ugly = pUglyNumbers[nextUglyIndex - 1];
delete[] pUglyNumbers;
return ugly;
}
int Min(int number1, int number2, int number3)
{
int min = (number1 < number2) ? number1 : number2;
min = (min < number3) ? min: number3;
return min;
}

技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

34丑数

标签:数组

原文地址:http://blog.csdn.net/wangfengfan1/article/details/46830549

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!