【剑指offer 面试题34】丑数

只包含因子2、3、5的数称作丑数。

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 int GetUglyNumber(int n)
 6 {
 7     if(n <= 0)
 8         return 0;
 9 
10     vector<int> UglyNum(n, 0);
11     UglyNum[0] = 1;
12 
13     vector<int>::iterator it2 = UglyNum.begin();
14     vector<int>::iterator it3 = UglyNum.begin();
15     vector<int>::iterator it5 = UglyNum.begin();
16 
17     int nextIndex = 1;
18     while(nextIndex < n)
19     {
20         int nextMin = min((*it2) * 2, min((*it3) * 3, (*it5) * 5));
21         UglyNum[nextIndex] = nextMin;
22 
23         while((*it2) * 2 <= UglyNum[nextIndex])
24             it2++;
25         while((*it3) * 3 <= UglyNum[nextIndex])
26             it3++;
27         while((*it5) * 5 <= UglyNum[nextIndex])
28             it5++;
29 
30         nextIndex++;
31     }
32 
33     return UglyNum[nextIndex - 1];
34 }
35 
36 int main()
37 {
38     cout<<GetUglyNumber(1500)<<endl;
39 }

 

posted @ 2015-07-09 21:13  tjuloading  阅读(159)  评论(0)    收藏  举报