[LeetCode] Ugly Number II

Stefan is a hero! Personally, I love his first C++ solution.

 1 class Solution {
 2 public:
 3     int nthUglyNumber(int n) {
 4         vector<int> ugly(n, 1);
 5         int c2 = 2, c3 = 3, c5 = 5;
 6         int i2 = 0, i3 = 0, i5 = 0;
 7         for (int i = 1; i < n; i++) {
 8             int last = ugly[i] = min(c2, min(c3, c5));
 9             while (c2 <= last) c2 = 2 * ugly[++i2];
10             while (c3 <= last) c3 = 3 * ugly[++i3];
11             while (c5 <= last) c5 = 5 * ugly[++i5];
12         }
13         return ugly[n - 1];
14     }
15 };

Well, refer to geeksforgeeks for more about ugly numbers!

posted @ 2015-08-19 16:32  jianchao-li  阅读(237)  评论(0编辑  收藏  举报