'''
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
'''
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
# target = 2**i * 3**j * 5**k
i = j = k = 0
l = [1]
while n > 1:
n_next = min(2*l[i], 3*l[j], 5*l[k])
if n_next == 2*l[i]:
i+=1
elif n_next == 3*l[j]:
j+=1
else:
k+=1
if n_next not in l:
l.append(n_next)
n-=1
return l[-1]
No comments:
Post a Comment