您的位置:首页 > Web前端

[剑指offer]丑数

2016-04-07 16:01 274 查看
/*
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;
//}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: