/*
34:> 丑数(因子只含2,3,5 : 6,8是,14不是)
习惯第一个丑数为 1
*/
int minNum(int val1, int val2, int val3)
{
int tmp = val1 < val2 ? val1 : val2;
return tmp < val3 ? tmp : val3;
}
int GetUglyNum(int index)
{
if (index < 0)
return 0;
int *pUglyNum = new int[index];
pUglyNum[0] = 1;
int nextUglyIndex = 1;
int *pMultiply2 = pUglyNum;
int *pMultiply3 = pUglyNum;
int *pMultiply5 = pUglyNum;
while (nextUglyIndex < index)
{
int _min = minNum(*pMultiply2*2, *pMultiply3*3, *pMultiply5*5);
pUglyNum[nextUglyIndex] = _min;
while (*pMultiply2 * 2 <= pUglyNum[nextUglyIndex])
pMultiply2++;
while (*pMultiply3 * 3 <= pUglyNum[nextUglyIndex])
pMultiply3++;
while (*pMultiply5 * 5 <= pUglyNum[nextUglyIndex])
pMultiply5++;
++nextUglyIndex;
}
int ugly = pUglyNum[nextUglyIndex-1];
delete[] pUglyNum;
return ugly;
}
//void test()
//{
// cout<<GetUglyNum(1500)<<endl;
//}
[剑指offer]丑数
最新推荐文章于 2020-11-29 15:59:49 发布