面试题34 丑数

题目描述

把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
 1 class Solution {
 2 public:
 3     int ugly;
 4     
 5     int min2(int a, int b){
 6         return a < b ? a : b;
 7     }
 8     
 9     int min(int a, int b, int c){
10         return min2(a, min2(b, c));
11     }
12         
13     int GetUglyNumber_Solution(int index) {
14         if (index <= 0)
15             return 0;
16         int *pUglyNumbers = new int[index];
17         pUglyNumbers[0] = 1;
18         int nextUglyIndex = 1;
19         int *pMultiply2 = pUglyNumbers;
20         int *pMultiply3 = pUglyNumbers;
21         int *pMultiply5 = pUglyNumbers;
22         
23         while (nextUglyIndex < index){
24             int minNum = min(*pMultiply2 * 2, *pMultiply3 * 3, *pMultiply5 * 5);
25             pUglyNumbers[nextUglyIndex] = minNum;
26             while (*pMultiply2 * 2 <= pUglyNumbers[nextUglyIndex])
27                 ++pMultiply2;
28             while (*pMultiply3 * 3 <= pUglyNumbers[nextUglyIndex])
29                 ++pMultiply3;
30             while (*pMultiply5 * 5 <= pUglyNumbers[nextUglyIndex])
31                 ++pMultiply5;
32             ++nextUglyIndex;
33         }
34         
35         ugly = pUglyNumbers[nextUglyIndex - 1];
36         delete[] pUglyNumbers;
37         return ugly;
38     }
39 };

 

posted @ 2016-04-06 11:05  早杰  阅读(126)  评论(0编辑  收藏  举报