题目:
把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
解答:
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
if index == 0:
return 0
uglys = [1]
t2 = 0
t3 = 0
t5 = 0
while len(uglys)<index:
newugly = min(uglys[t2]*2,uglys[t3]*3,uglys[t5]*5)
uglys.append(newugly)
if newugly % 2 == 0:
t2+=1
if newugly % 3 == 0:
t3+=1
if newugly % 5 == 0:
t5+=1
return uglys[index-1]