Skip to content

Commit 0a3c7a6

Browse files
Create ugly_numbers_ii.cpp
1 parent d0cda93 commit 0a3c7a6

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

ugly_numbers_ii.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
public:
3+
int nthUglyNumber(int n) {
4+
vector<int> ugly(n);
5+
ugly[0] = 1; //ugly of first number is 1
6+
7+
int i2 = 0, i3 = 0, i5 = 0;
8+
int nm2 = 2, nm3 = 3, nm5 = 5;
9+
int next_ugly_number = 1;
10+
11+
for(int i=1; i<n; i++) {
12+
next_ugly_number = min(nm2, min(nm3, nm5));
13+
ugly[i] = min(nm2 * ugly[i2], min(nm3 * ugly[i3], nm5 * ugly[i5]));
14+
if(ugly[i] == 2 * ugly[i2]) i2++;
15+
if(ugly[i] == 3 * ugly[i3]) i3++;
16+
if(ugly[i] == 5 * ugly[i5]) i5++;
17+
}
18+
return ugly[n-1];
19+
}
20+
};

0 commit comments

Comments
 (0)